首页 > 其他 > 详细

Contains Duplicate II

时间:2015-10-17 20:28:59      阅读:197      评论:0      收藏:0      [点我收藏+]

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 difference between i and jis at most k.

 

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        multimap<int, int> cpy;
        if(nums.empty())
            return false;
        int i = 0;
        for(auto num : nums)
        {
            if(cpy.find(num) != cpy.cend())
                {
                    auto bound = cpy.equal_range(num);
                    while(bound.first != bound.second)
                    {
                        int j = bound.first->second;
                        if(i - j <= k)
                            return true;
                        else
                            bound.first++;
                    }
                }
            cpy.insert({num, i++});
                
        }
        return false;
    }
};
  • multimap会保存同key的数据;相同key会相连保存
  • lower_bound()得到最小一个,upper_bound()得到最大一个
  • equal_range()得到一个pair,其中的first为lower_bound的值,second为upper_bound()的值
class Solution {  
public:  
    bool containsNearbyDuplicate(vector<int>& nums, int k) {  
        map<int, int> buf;  
        int n = nums.size();  
        for (int i = 0; i < n; i++)  
        {  
            if (buf.find(nums[i]) != buf.end() && i-buf[nums[i]] <= k)  
                return true;  
            else  
                buf[nums[i]] = i;  
        }  
  
        return false;  
    }  
};
  • map的insert插入已经存在的key时,不会覆盖原来的数据,会返回已经存在
  • map的下标赋值可以直接修改key对应的值

Contains Duplicate II

原文:http://www.cnblogs.com/dylqt/p/4887987.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!