Skip to content

Commit 2edd67d

Browse files
committedJan 18, 2025
Add solution #220
1 parent d712d7b commit 2edd67d

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@
154154
216|[Combination Sum III](./0216-combination-sum-iii.js)|Medium|
155155
217|[Contains Duplicate](./0217-contains-duplicate.js)|Easy|
156156
219|[Contains Duplicate II](./0219-contains-duplicate-ii.js)|Easy|
157+
220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard|
157158
225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy|
158159
226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy|
159160
229|[Majority Element II](./0229-majority-element-ii.js)|Medium|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 220. Contains Duplicate III
3+
* https://leetcode.com/problems/contains-duplicate-iii/
4+
* Difficulty: Hard
5+
*
6+
* You are given an integer array nums and two integers indexDiff and valueDiff.
7+
*
8+
* Find a pair of indices (i, j) such that:
9+
* - i != j,
10+
* - abs(i - j) <= indexDiff.
11+
* - abs(nums[i] - nums[j]) <= valueDiff, and
12+
*
13+
* Return true if such pair exists or false otherwise.
14+
*/
15+
16+
/**
17+
* @param {number[]} nums
18+
* @param {number} indexDiff
19+
* @param {number} valueDiff
20+
* @return {boolean}
21+
*/
22+
var containsNearbyAlmostDuplicate = function(nums, indexDiff, valueDiff) {
23+
if (valueDiff < 0) return false;
24+
25+
const map = new Map();
26+
27+
for (let i = 0; i < nums.length; i++) {
28+
const limit = valueDiff + 1;
29+
const item = Math.floor(nums[i] / limit);
30+
31+
if (map.has(item)
32+
|| map.has(item - 1) && Math.abs(nums[i] - map.get(item - 1)) < limit
33+
|| map.has(item + 1) && Math.abs(nums[i] - map.get(item + 1)) < limit) {
34+
return true;
35+
}
36+
37+
map.set(item, nums[i]);
38+
39+
if (i >= indexDiff) {
40+
map.delete(Math.floor(nums[i - indexDiff] / limit));
41+
}
42+
}
43+
44+
return false;
45+
};

0 commit comments

Comments
 (0)
Please sign in to comment.