A simple O(nlogk) Java solution with TreeMap.subMap()

  • 0
    public class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            TreeMap<Long, Integer> treeMap=new TreeMap<>();
            int n=nums.length; if (n==0 || k<1 || t<0) return false;
            for (int i=0;i<n;i++) {
                if (i>k) {
                    long x=(long)nums[i-k-1];
                    if (treeMap.get(x)==i-k-1) treeMap.remove(x);
                long u=(long)nums[i];
                if (!treeMap.subMap(u-t, true, u+t, true).isEmpty()) return true;
                treeMap.put(u, i);
            return false;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.