题目:https://leetcode.com/problems/contains-duplicate-ii/
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.
方法:用一个map,遍历数组,如果不在map中,就现在map里添加这个元素,如果能在map中找到这个值,那就看一下索引相差多少。
代码:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> map;
int l = nums.size();
for (int i = 0; i < l; i++)
{
if (map.find(nums[i]) != map.end() && i - map[nums[i]] <= k)
{
return true;
}
else map[nums[i]] = i;
}
return false;
}
};