Skip to content

Commit b300179

Browse files
committedMar 5, 2025
Add solution #532
1 parent 2357e82 commit b300179

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,7 @@
426426
528|[Random Pick with Weight](./0528-random-pick-with-weight.js)|Medium|
427427
529|[Minesweeper](./0529-minesweeper.js)|Medium|
428428
530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy|
429+
532|[K-diff Pairs in an Array](./0532-k-diff-pairs-in-an-array.js)|Medium|
429430
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
430431
542|[01 Matrix](./0542-01-matrix.js)|Medium|
431432
543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 532. K-diff Pairs in an Array
3+
* https://leetcode.com/problems/k-diff-pairs-in-an-array/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of integers nums and an integer k, return the number of unique k-diff
7+
* pairs in the array.
8+
*
9+
* A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:
10+
* - 0 <= i, j < nums.length
11+
* - i != j
12+
* - |nums[i] - nums[j]| == k
13+
*
14+
* Notice that |val| denotes the absolute value of val.
15+
*/
16+
17+
/**
18+
* @param {number[]} nums
19+
* @param {number} k
20+
* @return {number}
21+
*/
22+
var findPairs = function(nums, k) {
23+
const map = new Map();
24+
let result = 0;
25+
26+
for (const num of nums) {
27+
if (!map.has(num)) {
28+
if (!k) {
29+
map.set(num, 1);
30+
} else {
31+
if (map.has(num - k)) result++;
32+
if (map.has(num + k)) result++;
33+
map.set(num, 1);
34+
}
35+
} else if (!k && map.get(num) === 1) {
36+
result++;
37+
map.set(num, 2);
38+
}
39+
}
40+
41+
return result;
42+
};

0 commit comments

Comments
 (0)
Please sign in to comment.