217. Contains Duplicate

Total Accepted: 67962
Total Submissions: 169476
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.

C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        int n=nums.size();
        unordered_map<int,int> h;
        for(int i=0;i<n;++i){
            if(h.count(nums[i])){
                return true;
            }
            h[nums[i]]=1;
        }
        return false;
    }
};

看到了使用set的,表示佩服,代码只需一行

1
2
3
4
class Solution {  public:    bool containsDuplicate(vector<int>& nums) 
       return set<int>(nums.begin(), nums.end()).size() < nums.size();
    }
};

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。