您的位置:首页 > 大数据 > 人工智能

leetcode Contains Duplicate II

2015-12-14 20:45 441 查看
Given an array of integers and an integer k, find out whether 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.

这道题自己最后没有做出来,看的是【陆草纯】的解法。

如果是JAVA的hashmap的话很简单,但是C++没有,之前我也想过用map按值排序,半天实现不了。

先讲一下陆草纯的解法:

构建一个map,如果nums里的元素在map里没有出现过的话,就先保存下标。

如果出现过的话,就比较一下下标差值是否小于k。然后更新下标(每次都储存每个元素的最新下标)

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> vec;
int s=nums.size();
if(s==0||k==0) return false;
for(int i=0;i<s;i++){
if(vec.find(nums[i])==vec.end()){
vec[nums[i]]=i;
}
else {
if(i-vec[nums[i]]<=k) return true;
vec[nums[i]]=i;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: