Leetcode 220. Contains Duplicate III (Sliding window + set)

  1. Contains Duplicate III
    Hard
    You are given an integer array nums and two integers indexDiff and valueDiff.

Find a pair of indices (i, j) such that:

i != j,

abs(i - j) <= indexDiff.

abs(numsi - numsj) <= valueDiff, and

Return true if such pair exists or false otherwise.

Example 1:

Input: nums = 1,2,3,1, indexDiff = 3, valueDiff = 0

Output: true

Explanation: We can choose (i, j) = (0, 3).

We satisfy the three conditions:

i != j --> 0 != 3

abs(i - j) <= indexDiff --> abs(0 - 3) <= 3

abs(numsi - numsj) <= valueDiff --> abs(1 - 1) <= 0

Example 2:

Input: nums = 1,5,9,1,5,9, indexDiff = 2, valueDiff = 3

Output: false

Explanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.

Constraints:

2 <= nums.length <= 105

-109 <= numsi <= 109

1 <= indexDiff <= nums.length

0 <= valueDiff <= 109

解法1:这题要用到set的lower_bound函数,表示在set里面最小的那个>=输入值的那个元素。

cpp 复制代码
class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
        int n = nums.size();
        int left = 0, right = 0;
    //    unordered_map<int, int> mp; //<value, index>  注意用map不对,因为要检测map里面所有的entry,时间复杂度高。
        set<int> s;
        while (right < n) {
            //mp[nums[right]] = right;
            auto iter = s.lower_bound(nums[right]);
            if (iter != s.end()) {
                if (*iter - nums[right] <= valueDiff) return true;
            }
            iter = s.lower_bound(nums[right]);                
            if (iter != s.begin()) {
                iter--;
                if (nums[right] - *iter <= valueDiff) return true;
            }
            
            s.insert(nums[right]);
            right++;
            while (right - left > indexDiff) {
                s.erase(nums[left]);
                left++;
            }
        }
        return false;
    }
};
相关推荐
可编程芯片开发1 小时前
基于霍尔传感器和PID控制器的有功功率检测控制系统simulink建模与仿真
算法
To_OC1 小时前
LC 17 电话号码的字母组合:我的回溯算法,就是从这道题开窍的
javascript·算法·leetcode
战族狼魂4 小时前
GPT-5.6与Grok 4.5重磅发布
人工智能·算法·大模型·大语言模型
白日焰火14 小时前
基于 OpenSpec 实现规范驱动开发
算法·交互
imuliuliang5 小时前
关于图搜索算法的性能建模与可预测性研究7
算法
ForDreamMusk6 小时前
批量归一化
人工智能·算法·机器学习
Ivanqhz7 小时前
刚体的自由度
人工智能·算法
KaMeidebaby7 小时前
卡梅德生物技术快报|抗体合成:多肽抗体合成工程化方案:Nsp2 保守肽多抗制备与多维度验证
前端·网络·数据库·人工智能·算法
Yang_jie_038 小时前
笔记:数据结构(栈是否使用底指针以及头指针的初始化值)
数据结构·笔记·算法
2301_800895108 小时前
信息安全数学基础复习
算法