`
hcx2013
  • 浏览: 88754 次
社区版块
存档分类
最新评论

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.

 

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

 

4
8
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics