码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-219-Contains Duplicate II]

时间:2017-06-04 15:40:50      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:记录   amp   dice   size   diff   span   pre   log   leetcode   

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]

标签:记录   amp   dice   size   diff   span   pre   log   leetcode   

原文地址:http://www.cnblogs.com/hellowooorld/p/6940449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!