0
点赞
收藏
分享

微信扫一扫

220、存在重复的元素

给你一个整数数组 nums 和两个整数 k 和 t 。请你判断是否存在 两个不同下标 i 和 j,使得 abs(nums[i] - nums[j]) <= t ,同时又满足 abs(i - j) <= k 。

如果存在则返回 true,不存在返回 false。

解题方法一:滑动窗口+二分查找

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        int n = nums.size();
        set<long> s;
        for(int i = 0; i < n; ++i){
            auto iter = s.lower_bound((long)nums[i] - t);
            if(iter != s.end() && *iter <= (long)nums[i] + t) return true;
            s.insert(nums[i]);
            if(i >= k) s.erase(nums[i - k]); 
        }
        return false;
    }
};
举报

相关推荐

0 条评论