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;
    }
};
相关推荐
吃好睡好便好15 小时前
Matlab中三种三维图的对比
开发语言·人工智能·学习·算法·matlab·信息可视化
代码改善世界15 小时前
【C++进阶】二叉搜索树
java·数据结构·c++
1570925113415 小时前
回溯算法基础分享
算法·深度优先
脆皮炸鸡75515 小时前
进程通信----命名管道
linux·经验分享·笔记·算法·学习方法
如竟没有火炬16 小时前
至少有K个重复字符的最长子串
开发语言·数据结构·python·算法·leetcode·动态规划
想带你从多云到转晴16 小时前
优选算法---双指针
java·算法
小O的算法实验室16 小时前
2026年IEEE TSMC,基于Q学习平衡全局与局部搜索的防空资源分配问题进化算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
谙弆悕博士16 小时前
快速学C语言——第17章:多文件编程与头文件规范
c语言·开发语言·算法·学习方法·头文件·多文件编程
水蓝烟雨17 小时前
2359. 找到离给定两个节点最近的节点
算法·leetcode
澈20717 小时前
哈希表:O(1)查找的终极指南
算法·哈希算法·散列表