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 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对应的值
posted @ 2015-10-17 18:54  dylqt  阅读(122)  评论(0编辑  收藏  举报