219.Contains Duplicate II
219.Contains Duplicate II
难度:Easy
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.
1
Example 1:
2
3
Input: nums = [1,2,3,1], k = 3
4
Output: true
5
Example 2:
6
7
Input: nums = [1,0,1,1], k = 1
8
Output: true
9
Example 3:
10
11
Input: nums = [1,2,3,1,2,3], k = 2
12
Output: false
Copied!
新建一个map保存相同元素的索引值,然后比较相同元素索引值中相邻两个索引是否有满足条件的。
1
class Solution {
2
public:
3
bool containsNearbyDuplicate(vector<int>& nums, int k) {
4
unordered_map<int, vector<int >> cnt;
5
for(int i=0;i<nums.size();i++)
6
cnt[nums[i]].push_back(i);
7
for(auto c:cnt)
8
if(c.second.size()>1)
9
{
10
for(int i=1;i<c.second.size();i++)
11
if(c.second[i]-c.second[i-1]<=k)
12
return true;
13
}
14
return false;
15
}
16
};
Copied!
执行用时 :56 ms, 在所有 C++ 提交中击败了50.75%的用户 内存消耗 :22 MB, 在所有 C++ 提交中击败了5.03%的用户
Copy link