题目链接
tag:
- Easy;
question:
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 absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
思路:
这道题是之前那道Contains Duplicate 存在重复值的延伸,不同之处在于那道题只要我们判断下数组中是否有重复值,而这道题限制了数组中相邻有一组重复的数字,而且他们坐标差不能超过k。
我的错误思路是只考虑最开始的两个的重复数字 比如 1 0 1 1 我算出来的index差值为 2 但是给定 k=1 这种情况将要返回 false 但是应该返回 true,代码如下:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> m;
for (int i=0; i<nums.size(); ++i) {
if ((m.find(nums[i]) != m.end()) && (i- m[nums[i]] <= k))
return true;
m[nums[i]] = i;
}
return false;
}
};
网友评论