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;
    }
};
相关推荐
未来之窗软件服务1 小时前
自己写算法(九)网页数字动画函数——东方仙盟化神期
前端·javascript·算法·仙盟创梦ide·东方仙盟·东方仙盟算法
豐儀麟阁贵1 小时前
基本数据类型
java·算法
乐迪信息3 小时前
乐迪信息:基于AI算法的煤矿作业人员安全规范智能监测与预警系统
大数据·人工智能·算法·安全·视觉检测·推荐算法
hsjkdhs4 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
立志成为大牛的小牛4 小时前
数据结构——十七、线索二叉树找前驱与后继(王道408)
数据结构·笔记·学习·程序人生·考研·算法
星空下的曙光4 小时前
Node.js crypto模块所有 API 详解 + 常用 API + 使用场景
算法·node.js·哈希算法
Algo-hx4 小时前
数据结构入门 (七):从“链接”到“分支” —— 初探树与二叉树
数据结构
小贾要学习5 小时前
【数据结构】C++实现红黑树
数据结构·c++
StarPrayers.6 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法
爱吃橘的橘猫6 小时前
嵌入式系统与嵌入式 C 语言(2)
c语言·算法·嵌入式