217. Contains Duplicate

来源:互联网 发布:斯基德莫尔学院 知乎 编辑:程序博客网 时间:2024/05/16 03:55

Related Topics:Hash Table,Array

如果数组里的数字全部不重复则返回false,如果有一个数重复2次以上则返回true,哈希表key存数字,value存出现次数

class Solution {

public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int,int> hashmap;
        for(int i=0;i<nums.size();i++){
            int key=nums[i];
            unordered_map<int,int>::iterator iter = hashmap.find(key);
            if(iter == hashmap.end()){
                hashmap.insert(pair<int,int>(key,1));
            }
            else{
                (iter->second)++;
            }
        }
        for(unordered_map<int,int>::iterator iter = hashmap.begin();
                iter!=hashmap.end();iter++){
                    if((iter->second)>=2) return true;
        }
        return false;
    }
};