Contains Duplicate II
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 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=