LeetCode220. Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

解题思路:

1、创建set。(set内的元素为升序排序且唯一) 

2、设置大小为k的滑动窗口,判断nums[i]与滑动窗口中各值的绝对差是否小于t。

参考https://blog.csdn.net/lv1224/article/details/76627279

如复制到vector<long long>中超时。

lower_bound(key_value) ,返回第一个大于等于key_value的定位器

upper_bound(key_value),返回最后一个大于key_value的定位器

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        set<long long> s; //long long避免
        for(int i=0,j=0;i<nums.size();i++)
        {
            if(i-j>k)
            {
                s.erase(nums[j]);
                j++;
            }
            auto it=s.lower_bound((long long)nums[i]-t); //找到第一个大于等于nums[i]-t的,即左界限
            if(it!=s.end()&&abs(nums[i]-*it)<=t) //找到,且判断是否小于等于右界限
            {
                return true;
            }
            s.insert(nums[i]);
        }
        return false;
    }
};

 

 

LeetCode217. Contains Duplicate [C++] 

LeetCode219. Contains DuplicateII [C++]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值