C# Amortized O(n) using buckets


  • 0
    P
    public class Solution {
        public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if (null == nums || nums.Count() < 2 || k < 1 || t < 0){
                return false;
            }
            
            int n = nums.Count(), w = t;
            Dictionary<int,int> buckets = new Dictionary<int,int>();
            for (int i = 0; i < n; i++){
                int buck = nums[i]/Math.Max(1, w);
                if ((buckets.ContainsKey(buck) && Math.Abs((long)(buckets[buck]-nums[i])) <= t)
                 || (buckets.ContainsKey(buck-1) && Math.Abs((long)(buckets[buck-1]-nums[i])) <= t)
                 || (buckets.ContainsKey(buck+1) && Math.Abs((long)(buckets[buck+1]-nums[i])) <= t)){
                    return true;
                }
                
                buckets[buck] = nums[i];
                if (i >= k){
                    buckets.Remove(nums[i-k]/Math.Max(1,w));
                }
            }
            
            return false;
        }
    }
    

Log in to reply
 

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