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 i and j is at most k.
方法很简单:和之前的那道题目类似,也是用map。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> kvmap;
for(int i=0; i<nums.size(); i++)
{
map<int, int>::iterator tmp_iter=kvmap.find(nums[i]);
if(tmp_iter==kvmap.end())//之前没有这样的数字,此数字首次出现
kvmap[nums[i]]=i;
else
if( i-kvmap[nums[i]]<=k)//出现了之前已经出现过的数字
return true;
else
kvmap[nums[i]]=i;//更新最近出现的位置
}
return false;
}
};leetcode_Contains Duplicate II_easy
原文地址:http://blog.csdn.net/u013861066/article/details/46300333