leetcode [220]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

题目大意:

给定一个整数数组nums,一个整数k,一个整数n。要求判断数组nums中是否存在不同的两个索引下标i和j,使得 |i - j| <= k 并且 |nums[i] - nums[j]| <= t。

解法:

使用一个treeset维持大小为k的有序窗口,判断在当前窗口中是否存在与当前数的绝对值小于t的。

class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(nums==null||nums.length==0||k<1||t<0) return false;
        TreeSet<Integer>values=new TreeSet<>();
        for(int i=0;i<nums.length;i++){
            Integer floor=values.floor(nums[i]+t);
            Integer ceil=values.ceiling(nums[i]-t);
            if((floor!=null&&(long)nums[i] - (long)floor <= t)
                    ||(ceil!=null&&(long)ceil - (long)nums[i] <= t)) return true;
            values.add(nums[i]);
            if(i>=k) values.remove(nums[i-k]);
        }

        return false;
    }
}

  参考https://blog.csdn.net/smart_ferry/article/details/89668441,使用hashset来保存窗口。

class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(nums==null||nums.length==0||k<1||t<0) return false;

        HashSet<Integer>set=new HashSet<>();
        for(int i=0;i<nums.length;i++){
            if(t==0){
                if(set.contains(nums[i])) return true;
            }else{
                for(int a:set){
                    if(Math.abs((long)a-(long)nums[i])<=t) return true;
                }
            }
            set.add(nums[i]);
            if(i>=k) set.remove(nums[i-k]);
        }

        return false;
    }
}

  

posted @ 2019-04-29 15:47  小白兔云  阅读(118)  评论(0)    收藏  举报