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.

Solution:

  1. public class Solution {
  2. public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
  3. TreeSet<Integer> tree = new TreeSet<>();
  4. for (int i = 0; i < nums.length; i++) {
  5. Integer ceil = tree.ceiling(nums[i] - t);
  6. Integer floor = tree.floor(nums[i] + t);
  7. if ((ceil != null && ceil <= nums[i]) || (floor != null && floor >= nums[i])) {
  8. return true;
  9. }
  10. tree.add(nums[i]);
  11. if (i >= k) {
  12. tree.remove(nums[i - k]);
  13. }
  14. }
  15. return false;
  16. }
  17. }