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;
    }
};
相关推荐
Polevne3 分钟前
C# GRPC 一元与双向流
linux·算法·c#
huang5791476 分钟前
复杂网络中的最短路径搜索算法性能分析3
算法
找方案10 分钟前
AI+气象预报:华为盘古大模型如何让天气预报精准到街区
人工智能·算法·机器学习
Yingye Zhu(HPXXZYY)25 分钟前
洛谷B4337 [中山市赛 2023] 简单数学题
c++·算法
郝学胜-神的一滴28 分钟前
C++11 工程级应用 12:编译期类型魔法,干掉重复与臃肿的代码
开发语言·数据结构·c++·软件工程·visual studio
kyle~35 分钟前
数据结构---红黑树
数据结构
pen-ai35 分钟前
【优化方法】为什么梯度是最陡峭的方向?
人工智能·算法·机器学习·最小二乘法
个 人 练 习 生37 分钟前
数据结构:排序算法详解
c语言·数据结构·经验分享·学习·算法·排序算法
青山木1 小时前
枚举类DP进阶:完全平方数与零钱兑换
java·数据结构·算法·leetcode·动态规划
huang5791471 小时前
从缓存行角度优化链表遍历:批处理与预取策略
数据结构·链表·缓存