Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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<int, int>, 其中key = A[i], value = i;
还想到, 同一个key可以挂多个value. 所以就有了下面的代码.
自己代码:

bool containsNearbyDuplicate(vector<int>& A, int k) {
    map<int, int> map;
    for (int i = 0; i < A.size(); i++) {
        if (map.find(A[i]) != map.end() && (i - map[A[i]]) <= k)
            return true;
        map[A[i]] = i;
    }
    return false;
}

人家代码:

人家代码, 用set
核心是: 维护一个set,其中只包含i之前的k个元素,有重复的也会被set干掉.
如k=3, 当前i=4, 下面indx=0的元素应从set中删除!
0       1 2 3      4
bool containsNearbyDuplicate(vector<int>& A, int k) {
    unordered_set<int> set; //基于hash实现,比set查询速度快
    if (k < 0) return false;
    for (int i = 0; i < A.size(); i++) {
        if (i > k) set.erase(A[i - k - 1]);
        if (set.find(A[i]) != set.end()) return true;
        set.insert(A[i]);
    }
    return false;
}
posted on 2017-08-14 12:00  英雄与侠义的化身  阅读(81)  评论(0编辑  收藏  举报