LeetCode:Contains Duplicate

Problem:

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.

 

Solution:用hashmap来计数判断重复次数

class Solution {
    //map计数
public:
    bool containsDuplicate(vector<int>& nums) {
        
        unordered_map<int,int> mapping;
        if(nums.size()==0) return false;
        //初始化
        for(int i=0;i<nums.size();i++)
        {
            mapping[nums[i]]=0;
            
        }
        
        for(int i=0;i<nums.size();i++)
        {
            if(++mapping[nums[i]]>=2) return true;        
        }
        return false;
    }
};

 

posted @ 2015-06-08 10:22  尾巴草  阅读(119)  评论(0编辑  收藏  举报