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+1大小的map,因为若有相同元素,删除元素时会将新加入的相同大小的元素删掉,导致错误。

 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         map<int,int> hmap;
 5         int n=nums.size();
 6         if(n<2) return false;
 7         for(int i=0;i<n;i++)
 8         {
 9             if(hmap.count(nums[i])&&i-hmap[nums[i]]<=k)
10                 return true;
11             else
12                 hmap[nums[i]]=i;
13             
14         }
15         return false;
16     }
17 };

 

相关文章:

  • 2021-09-04
  • 2021-06-16
  • 2022-01-24
  • 2021-07-05
  • 2021-07-22
猜你喜欢
  • 2021-09-21
  • 2021-07-09
  • 2022-01-19
  • 2021-07-31
  • 2021-06-16
相关资源
相似解决方案