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;
    }
};
相关推荐
宵时待雨2 分钟前
C++笔记归纳10:继承
开发语言·数据结构·c++·笔记·算法
田梓燊6 分钟前
最长的连续序列到底怎么写
算法·哈希算法·散列表
smchaopiao10 分钟前
C++20概念(Concepts)入门指南
开发语言·c++·算法
一叶落43814 分钟前
LeetCode 21. 合并两个有序链表(C语言详解 | 链表经典题)
c语言·数据结构·c++·算法·leetcode·链表
阿里嘎多哈基米27 分钟前
速通Hot100-Day04——哈希
数据结构·算法·leetcode·哈希算法·散列表
WolfGang00732132 分钟前
代码随想录算法训练营 Day10 | 栈与队列 part02
数据结构
飞天狗11143 分钟前
最短路算法
算法
汉克老师1 小时前
GESPC++考试五级语法知识(二、埃氏筛与线性筛)课后习题
算法·线性筛·素数·gesp5级·gesp五级·埃氏筛·筛法
xsyaaaan1 小时前
leetcode-hot100-普通数组:53最大子数组和-56合并区间-189轮转数组-238除了自身以外数组的乘积-41缺失的第一个正数
leetcode
0 0 01 小时前
洛谷P4427 [BJOI2018] 求和 【考点】:树上前缀和
开发语言·c++·算法·前缀和