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 between i and j is at most k.

 

在数组中找两个相等的数,如果他们索引之差的绝对值  <= k  则返回true

 

C++(26ms):

 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         unordered_set<int> s ;
 5         int len = nums.size() ;
 6         for (int i = 0 ; i < len ; i++){
 7             if (i > k)
 8                 s.erase(nums[i-k-1]) ;
 9             if (!s.insert(nums[i]).second)
10                 return true ;
11         }
12         return false ;
13     }
14 };

 

 

 

C++(155ms):

 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         unordered_map<int,int> Map ;
 5         int len = nums.size() ;
 6         bool flag = false ;
 7         for (int i = 0; i < len;i++ ){
 8             if (Map[nums[i]]){
 9                 int t = abs(i+1 - Map[nums[i]]) ;          
10                 Map[nums[i]] = i+1 ;
11                 if (t <= k){
12                     flag = true ;
13                     break ;
14                 }   
15             }else{
16                 Map[nums[i]] = i+1 ;
17                 cout<<Map[nums[i]]<<endl ;
18             }
19         }
20         if (flag)
21             return true ;
22         else
23             return false ;
24         }
25 };

 

posted @ 2017-09-25 11:06  __Meng  阅读(107)  评论(0编辑  收藏  举报