标签:style distinct key and bsp needed turn diff absolute
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Note: C# type conversion is pretty tricky, the rule is to do conversion in all the places needed.
1 public class Solution { 2 public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) { 3 if (t < 0 || k < 0) return false; 4 5 long bucketLen = (long)t + 1; 6 var dict = new Dictionary<long, long>(); 7 8 for (int i = 0; i < nums.Length; i++) 9 { 10 long n = (long)((long)nums[i] - Int32.MinValue); 11 var key = n / bucketLen; 12 13 if (dict.ContainsKey(key) || (dict.ContainsKey(key - 1) && (n - dict[key - 1] <= t)) || (dict.ContainsKey(key + 1) && (dict[key + 1] - n <= t))) 14 { 15 return true; 16 } 17 18 dict[key] = n; 19 20 if (i >= k) 21 { 22 dict.Remove((long)((long)nums[i - k] - Int32.MinValue) / bucketLen); 23 } 24 } 25 26 return false; 27 } 28 }
Leetcode 220: Contains Duplicate III
标签:style distinct key and bsp needed turn diff absolute
原文地址:http://www.cnblogs.com/liangmou/p/7952952.html