Fork me on GitHub

[leetcode-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.

思路:

用一个map,记录关键字和下标。

bool containsNearbyDuplicate(vector<int>& nums, int k) 
{
  if(nums.size()<=1 || k<=0) return false;
  map<int,int>m;
  for(int i=0;i<nums.size();i++)
  {
    if(m.count(nums[i]) && abs(m[nums[i]]-i)<=k)
    {
      return true;
    }
    else
    {
      m[nums[i]] = i;
    }
  }
  return false;  
}

 

 

 

 
posted @ 2017-06-04 14:29  hellowOOOrld  阅读(151)  评论(0编辑  收藏  举报