|
| 1 | +package com.interview.misc; |
| 2 | + |
| 3 | +import java.util.Map; |
| 4 | +import java.util.TreeMap; |
| 5 | + |
| 6 | +/** |
| 7 | + * Date 10/26/2016 |
| 8 | + * @author Tushar Roy |
| 9 | + * |
| 10 | + * Given an array of integers, |
| 11 | + * find out whether there are two distinct indices i and j in the array such that the difference |
| 12 | + * between nums[i] and nums[j] is at most t and the difference between i and j is at most k. |
| 13 | + * |
| 14 | + * Solution |
| 15 | + * Keep a tree map of num and its count. For every new number check if any number exists in map between |
| 16 | + * num - t and num + t. If yes than return true. If no then add this number to the tree map. Also if tree map |
| 17 | + * becomes of size k then drop the num[i - k] number from the tree map. |
| 18 | + * |
| 19 | + * Time complexity O(nlogk) |
| 20 | + * |
| 21 | + * https://leetcode.com/problems/contains-duplicate-iii/ |
| 22 | + */ |
| 23 | +public class ContainsNumberWithinKDistance { |
| 24 | + |
| 25 | + public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { |
| 26 | + if (nums.length == 0 || k == 0) { |
| 27 | + return false; |
| 28 | + } |
| 29 | + TreeMap<Integer, Integer> map = new TreeMap<>(); |
| 30 | + for (int i = 0; i < nums.length; i++) { |
| 31 | + int lowerEntry = nums[i] - t - 1; |
| 32 | + int higherEntry = nums[i] + t + 1; |
| 33 | + Map.Entry<Integer, Integer> higher = map.lowerEntry(higherEntry); |
| 34 | + if (higher != null && higher.getKey() >= nums[i]) { |
| 35 | + return true; |
| 36 | + } |
| 37 | + Map.Entry<Integer, Integer> lower = map.higherEntry(lowerEntry); |
| 38 | + if (lower != null && lower.getKey() <= nums[i]) { |
| 39 | + return true; |
| 40 | + } |
| 41 | + if (map.size() == k) { |
| 42 | + map.compute(nums[i - k], (key, val) -> { |
| 43 | + if (val == 1) { |
| 44 | + return null; |
| 45 | + } else { |
| 46 | + return val - 1; |
| 47 | + } |
| 48 | + }); |
| 49 | + } |
| 50 | + map.compute(nums[i], (key, val) -> { |
| 51 | + if (val == null) { |
| 52 | + return 1; |
| 53 | + } else { |
| 54 | + return val + 1; |
| 55 | + } |
| 56 | + }); |
| 57 | + } |
| 58 | + return false; |
| 59 | + } |
| 60 | +} |
0 commit comments