ITPub博客

首页 > > > [LeetCode] Contains Duplicate II

[LeetCode] Contains Duplicate II

作者:Ruiyuan Li 时间:2015-05-30 00:00:00 0 删除 编辑

Contains Duplicate II

 Given an array of integers and an integer k, return true if and only if there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

解题思路:

可以用一个set记录滑动窗口大小的所有元素,随着滑动窗口往右移,左边的陆续删除,添加右边的。若set中出现相同元素,那么返回true。否则返回false。注意题意中的k是指j-i=k。

class Solution {
public:
    bool containsNearbyDuplicate(vector& nums, int k) {
        int len = nums.size();
        if(k <= 0 || len<=0){
            return false;
        }
        set s;
        for(int i = 0; ik){
                s.erase(nums[i - k - 1]);
            }
            if(s.find(nums[i])!=s.end()){
                return true;
            }
            s.insert(nums[i]);
        }
        return false;
    }
};


转载请注明: » [LeetCode] Contains Duplicate II
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4824