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(nums[i] - nums[j]) <= 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(nums[i] - nums[j]) <= 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 <= nums[i] <= 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;
    }
};
相关推荐
二向箔reverse8 分钟前
机器学习算法核心总结
人工智能·算法·机器学习
猿究院--冯磊1 小时前
JVM垃圾收集器
java·jvm·算法
野犬寒鸦1 小时前
力扣hot100:最大子数组和的两种高效方法:前缀和与Kadane算法(53)
java·后端·算法
我家大宝最可爱2 小时前
动态规划:入门思考篇
算法·动态规划·代理模式
肉夹馍不加青椒2 小时前
第三十三天(信号量)
java·c语言·算法
古译汉书3 小时前
嵌入式-SPI番外之按钮驱动程序的编写-Day15
c语言·stm32·单片机·嵌入式硬件·mcu·算法
快去睡觉~3 小时前
力扣48:旋转矩阵
算法·leetcode·矩阵
卡洛斯(编程版5 小时前
(1) 哈希表全思路-20天刷完Leetcode Hot 100计划
python·算法·leetcode
NAGNIP6 小时前
DeepSeekMoE 架构解析
算法
不喜欢学数学er6 小时前
算法第五十二天:图论part03(第十一章)
算法·深度优先·图论