Leetcode 220: Contains Duplicate III
Posted Keep walking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 220: 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 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的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode]220. Contains Duplicate III
[LeetCode] 220. Contains Duplicate III Java
Leetcode 220. 存在重复元素 III (Contains Duplicate III)
leetcode 220. Contains Duplicate III 求一个数组中有没有要求的元素 ---------- java