leetCode(28):Contains Duplicate II

Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.

哈希表的使用

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        map<int,int> value;
    	for(int i=0;i<nums.size();++i)
    	{
    		if(value.find(nums[i])!=value.end()  &&  i-value[nums[i]]<=k)
    			return true;  
    		value[nums[i]]=i;
    	}
    	return false;
    }
};


posted @ 2016-04-13 16:38  blfshiye  阅读(112)  评论(0编辑  收藏  举报