220. Contains Duplicate III
LeetCode 220. Contains Duplicate III
Description
Given an integer array nums
and two integers k
and t
, return true
if there are two distinct indices i
and j
in the array such that abs(nums[i] - nums[j]) <= t
and abs(i - j) <= k
.
Example 1:
Example 2:
Constraints:
0 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
0 <= k <= 104
0 <= t <= 231 - 1
Tags
Sort, Ordered Map
Solution
We initialize a map to store a set of buckets. The size of each bucket is t+1
. Iterate over nums, we first obtain the bucket which the current element maps to. If there has already been an element in this bucket, we return true. Or, if the adjacent buckets hold elements and the difference between any one of the them and the current element is within t
, return true. After evaluating, we put the current element to the corresponding bucket, and remove the bucket which nums[i-k]
maps to. Finally, we return false since no qualified element found.
Complexity
Code
Reference
Last updated
Was this helpful?