leetcode 219. Contains Duplicate II | 滑窗, Set

Description

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.

My solution

想法主要有两个:
1. 参照leetcode 217的方法, argsort一下, 对于相邻元素判断是否相同, 注意这里sort返回索引, 加一步判断索引差值即可. 这个思路用python较好实现.
2. 建立一个dict, key是nums的元素, value是其索引(用list方式存储), 判断一下同一个key多value的value之差.
上述两种思路都有点复杂, 同时, 因为题干只要求return bool, 自己的做法仍然是抠出来所有情况, 是有很大冗余的.

Discuss

采用滑窗方式, 窗口大小为题干中的k. 维护一个大小为k的set, 如果窗口范围内, 有新的重复元素来到, 是与set的无重复性冲突的.

bool containsNearbyDuplicate(vector<int>& nums, int k) {
    set<int> cand;
    for (int i = 0; i < nums.size(); i++) {
        if (i > k) cand.erase(nums[i-k-1]);
        if (!cand.insert(nums[i]).second) return true;
    }
    return false;
}

关于.second解释如下:

I searched online and found the answer.
The pair::first will store either the newly inserted element or the elements that has its same value in the set.
The pair::second will indicate the success or failure of inserting the new value.
We can use the followings:
if(!set.insert(item).second){
the content of insert failure to user;
}
Thanks

Reference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值