leetcode 220. Contains Duplicate III

本文探讨了一种使用滑动窗口与映射表解决数组中寻找特定条件下的相似元素问题的方法。通过确保映射表内键的索引差不超过预设值k,并查找与当前元素差值不超过t的值,有效解决了此问题。文章提供了详细的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] andnums[j] is at most t and the difference between i and j is at most k.


一开始以为和前两道差不多,做了之后发现不太一样,如果用前两道题的方法,一般都会超时,即使判断t和k大小分别用不同的方式还是超时。

所以采用滑动窗口,保证map里面的所有key下标只差在k以内,然后找一个和nums[i]差值在t以内的值。

lower_bound(x)和upper_bound的区别:

lower_bound(x)返回一个key>=x的iterator

upper_bound(x)返回一个key>x的iterator

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        map<int, int> mp;
        int j = 0;
        map<int, int>::iterator it = mp.end();
        for(int i = 0; i < nums.size(); i++){
            if(i - j > k) mp.erase(nums[j++]);
            it = mp.lower_bound(nums[i]-t);
            if(it != mp.end() && it->first - nums[i] <= t)return true;
            mp[nums[i]] = i;
        }
        return false;
    }
};







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值