LeetCode: 219. Contains Duplicate II
LeetCode: 219. 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 betweeni
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
解题思路
依次遍历数组,用 map
记录当前数字的最近出现的位置,当位置差小于 k
时返回 true
。
AC 代码
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> num2Idx;
bool bRet = false;
for(int i = 0; i < nums.size(); ++i)
{
if(num2Idx.find(nums[i]) == num2Idx.end() || i - num2Idx[nums[i]] > k)
{
num2Idx[nums[i]] = i;
}
else
{
bRet = true;
break;
}
}
return bRet;
}
};