leetcode解题报告(19):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.

分析

我的想法是:遍历该数组,并判断当前元素之后有没有和该元素相等的元素,如果有,就通过distance得到这两个值之间的长度,如果小于等于k,则返回true,否则继续遍历。

代码如下:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if(nums.size() == 0)return false;
        if(k <= 0)return false;
        for(auto it = nums.begin(); it != nums.end(); ++it){
            if(it + 1 == nums.end())return false;
            auto f = find(it + 1,nums.end(),*it);
            if(f != nums.end()){
                if(distance(it,f) <= k)return true;
            }
        }
        return false;
    }
};

然而测试用例中最后一个数组超时了,没ac,想了一会儿后还是不知道怎么优化这个解法,于是看了下讨论区:
https://discuss.leetcode.com/topic/15012/share-my-easy-to-understand-c-code

代码看到就懂了,还是用unordered_map,以元素值为key,元素下标为value。 遍历该数组,如果该元素不在数组中,就把元素放到这个unordered_map里。否则,判断当前元素下标与map中该元素的下标之差是否小于等于k,如果是,返回true。

代码如下:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if(nums.size() == 0)return false;
        unordered_map<int,int>m;
        for(int i = 0; i != nums.size(); ++i{
            if(m.find(nums[i]) != m.end() && i - m[nums[i]] <= k)
                return true;
            m[nums[i]] = i;
        }
        return false;
    }
};

我的解法和上述解法在复杂度上相比,主要是多了distance这个函数。不过影响复杂度的主要因素是find函数。

为了查找一个范围内的值,我调用的是stl里的find函数,而这个算法的性能会略低于map自己的find函数。此外,unordered_map的一些操作的复杂度也确实低于vector。

unordered_map大法好~

posted @ 2017-05-08 22:34  larryking  阅读(209)  评论(0编辑  收藏  举报