题目:
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 iand j is
at most k.
给定整型数组和整数k,查找是否存在两个相等的数它们的下标之差 <= k。
思路:
使用map保存值和位置。
代码:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_map<int , int> map;//键是nums[i],值是i
for(int i = 0 ; i < nums.size(); i++)
{
if(map.find(nums[i]) != map.end() && (i - map[nums[i]] <= k))
return true;
map[nums[i]] = i;//如果已经存在nums[i],则会取代之前的值
}
return false;
}
};