leetcode 217. Contains Duplicate

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.

用sort或则 unorder_map,map 什么的都可以吧

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        if (nums.size() <= 1) return false;
        for (int i = 1; i < nums.size(); ++i) {
            if ((nums[i] ^ nums[i - 1]) == 0) {
                return true;
            } 
        }
        return false;
    }
};

 

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int, int> umap;
        for(int i=0;i<nums.size();i++){
            if(umap.find(nums[i]) != umap.end())
                return true;
            umap[nums[i]] = 1;
        }
        return false;
    }
};

 

posted on 2017-07-28 16:34  Beserious  阅读(196)  评论(0编辑  收藏  举报