219. Contains Duplicate II

1.描述

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.

2.分析

用集合s存放最大距离为k之间的数组元素,依次遍历数组。
放入规则:遍历数组元素为nums[i],在集合s中查找nums[i]是否在集合中,如果在,则返回true。
取出规则:遍历数组元素为nums[i],如果i>k, 则从集合中取出nums[i-k-1]。

3.代码

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if (k <= 0) return false;
        if (k > nums.size()) k = nums.size() - 1;
        unordered_set<int> s;
        for (int i = 0; i < nums.size(); ++i) {
            if (i > k) s.erase(nums[i-k-1]);
            if (s.find(nums[i]) != s.end()) return true;
            s.insert(nums[i]);
        }
        return false;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容