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 };

 

posted @ 2015-07-29 16:13  鸭子船长  阅读(144)  评论(0编辑  收藏  举报