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 difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

Show Tags
Show Similar Problems

Have you met this question in a real interview? 

思路: Using binary search tree to storage the element.


public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        TreeSet<Long> set = new TreeSet<>();
        for(int i = 0; i < nums.length; i++) {
            if(i > k) set.remove(Long.valueOf(nums[i - k - 1]));
            long upperBound = (long)nums[i] + t;
            long lowerBound = (long)nums[i] - t;
            Long lower = set.lower(upperBound + 1);
            if(lower != null && lower >= lowerBound) return true;
            set.add(Long.valueOf(nums[i]));
        }
        return false;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章