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;
    }
};
相关推荐
XY_墨莲伊1 小时前
【算法设计与分析】实验5:贪心算法—装载及背包问题
c语言·数据结构·c++·算法·贪心算法·排序算法
Happy_Traveller2 小时前
三角形的最大周长(976)
数据结构·算法·leetcode
水蓝烟雨2 小时前
[HOT 100] 2824. 统计和小于目标的下标对数目
算法·hot 100
KuaCpp2 小时前
搜索与图论复习2最短路
c++·算法·图论
weixin_307779132 小时前
Python获取能唯一确定一棵给定的树的最少数量的拓扑序列
数据结构·python
咒法师无翅鱼3 小时前
【leetcode详解】T598 区间加法
算法·leetcode·职场和发展
砂糖はいかがですか。3 小时前
关于合并两个有序链表
数据结构·算法·链表
c-c-developer3 小时前
C++ Primer 自定义数据结构
数据结构·c++
不会打代码呜呜呜呜3 小时前
小白零基础--CPP多线程
开发语言·c++·算法
辰尘_星启4 小时前
【单层神经网络】基于MXNet的线性回归实现(底层实现)
算法·线性回归·mxnet