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

[leetcode] 219. Contains Duplicate II

2016-07-27 12:08 316 查看
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.

解法一:

runtime error的naive思路。

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

}
};

解法二:
感觉每道题都是脑筋急转弯。。。下面的思路就是用hash table记录数字的值和坐标,如果该值在之前出现过并且映射的坐标值和i只差不大于k, 返回true。

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

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  easy leetcode