Leetcode 220. 存在重复元素 III

文章讨论了如何优化一个检查近乎重复元素的代码,原始版本时间复杂度过高。作者提出使用哈希表和排序结合的方法,以及另一种更高效的方法,利用multiset和lower_bound操作,通过哨兵确保边界条件下的正确性。

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

**思路:首先声明这是一个没有通过的代码。最后一个循环样例超时了。
**
在这里插入图片描述
但是仍然可以反思一些东西:代码思路是:先将坐标哈希起来,然后遍历原数组去重后数组,然后依次判断是否满足条件,可以看到,如果是循环数组的话,复杂度非常高,…很乱我自己都晕了。总之不对。。。

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
        unordered_map<int, vector<int>> hash;
        for(int i = 0; i < nums.size(); i ++ )
            hash[nums[i]].push_back(i);

        sort(nums.begin(), nums.end());
        vector<int> temp;
        for(int i = 0; i < nums.size(); i ++ ) {
            while(i + 1 < nums.size() && nums[i] == nums[i + 1]) i ++;
            temp.push_back(nums[i]);
        }
        cout << temp.size() << endl;
        for(int l = 0; l < temp.size(); l ++) {
            int r = l;
            while(r < temp.size() && abs(temp[l] - temp[r]) <= valueDiff) {
                auto a = hash[temp[l]], b = hash[temp[r]];
                for(auto x : a)
                    for(auto y : b) {
                        if(abs(x - y) <= indexDiff && x != y) {
                            return true;
                        }    
                    }
                r ++;
            }
        }
        return false;
    }
};

看y总写的:
在这里插入图片描述

思路就是维护一段区间长度不超过indexDiff,并在区间内利用lower_bound操作找到一个大于等于x的最小的数,判断,再找到小于等于x的最大的数,判断。
主要是要能想到这种数据结构,和lower_bound操作会简单很多。

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
        typedef long long LL;
        multiset<LL> S;
        S.insert(1e18), S.insert(-1e18);
        for(int i = 0, j = 0; i < nums.size(); i ++ ) {
            if(i - j > indexDiff) S.erase(S.find(nums[j ++ ]));
            int x = nums[i];
            auto it = S.lower_bound(x);
            if(*it - x <= valueDiff) return true;
            -- it;
            if(x - *it <= valueDiff) return true;
            S.insert(x);
        }
        return false;
    }
};

其中 S.insert(1e18), S.insert(-1e18);这一行的作用是向 multiset 容器 S 中插入两个极大和极小的值,即正无穷和负无穷(一般叫哨兵)。这样做的目的是确保 multiset 中始终存在两个元素,这两个元素是无穷大和无穷小,以确保在 lower_bound 操作时即使没有满足条件的元素也能够正确返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值