forked from dnshi/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKdiffPairsInAnArray.js
More file actions
36 lines (31 loc) · 798 Bytes
/
KdiffPairsInAnArray.js
File metadata and controls
36 lines (31 loc) · 798 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Source : https://leetcode.com/problems/k-diff-pairs-in-an-array/?tab=Description
// Author : Dean Shi
// Date : 2017-03-10
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findPairs = function(nums, k) {
if (k < 0) return 0
const numsSet = new Set()
const data = new Set(nums)
let count = 0
nums.forEach((n) => {
if (numsSet.has(n)) return
if (k !== 0) {
if (data.has(k + n) && !numsSet.has(k + n)) {
count++
}
if (data.has(n - k) && !numsSet.has(n - k)) {
count++
}
} else {
if (nums.indexOf(n) !== nums.lastIndexOf(n)) {
count++;
}
}
numsSet.add(n)
})
return count
};