导航

LeetCode Contains Duplicate II

Posted on 2016-03-31 00:49  CSU蛋李  阅读(152)  评论(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.

 

  题目的大意:给你一个int型的数组和k,看看在数组中,是否有两个不同的索引i和j使得nums[i]=nums[j],i和j的差值,最多为k

 

首先想到的办法是一个一个数字的比,两个for循环即可得到结果。但是这种方法耗时过长,提交后没过。这时需要考虑建一个multimap

将数组的值和索引存到里面去,这样就快的多了。理所当然,提交也通过了

 

class Solution {
public:
   bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if (nums.size()<2 || k<1)return false;
        else
        {
            multimap<int, int> mulm;
            for (int i = 0;i < nums.size();++i)
                mulm.insert(make_pair(nums[i], i));
            for (int i = 0;i < nums.size();++i)
            {
                auto cnt = mulm.count(nums[i]);
                auto iter = mulm.find(nums[i]);
                while (--cnt) {
                    int pre = iter->second;
                    int real = (++iter)->second-pre;
                    if (real <= k)return true;
                }
            }
        }
        return false;
   }
};