Contains Duplicate【217】

Datetime:2016-08-23 01:22:44          Topic: LeetCode           Share

217. Contains Duplicate

My Submissions

Total Accepted:  58633 Total Submissions:  149186 Difficulty:  Easy

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Subscribe to see which companies asked this question

Hide Tags
Array   Hash Table
//思路首先:用数据结构set来做,因为他是红黑树为底层,所以查找某个元素时间浮渣度较低,并且set不允许相同元素出现
//如果某个元素的count为0则,插入到set,如果不为0,return false
//set的查找时间为O(lg(N))所以最终时间浮渣度为O(Nlg(N))
class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
    if(nums.empty())
        return false;
    set<int> s;
    s.insert(nums[0]);
     for(int i=1;i<nums.size();i++)
     {
         if(!s.count(nums[i]))
             s.insert(nums[i]);
         else
             return true;
     }
     return false;
    }
};




About List