首页 > 代码库 > [leetcode-219-Contains Duplicate II]

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

 

 

 

 

[leetcode-219-Contains Duplicate II]