-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution1.js
54 lines (45 loc) · 815 Bytes
/
solution1.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* https://leetcode.com/problems/k-diff-pairs-in-an-array/
*
* 532. K-diff Pairs in an Array
*
* Easy
*
* 52ms 100%
* 37.9mb 70.39%
*/
const findPairs = (nums, k) => {
if (k < 0) {
return 0
}
if (k === 0) {
let ans = 0
const m = new Map()
for (let i = 0, max = nums.length; i < max; i++) {
const num = nums[i]
m.set(num, (m.get(num) || 0) + 1)
}
for (let [key, value] of m) {
if (value > 1) {
ans++
}
}
return ans
}
const cache = new Set()
let ans = 0
for (let i = 0, max = nums.length; i < max; i++) {
const num = nums[i]
if (cache.has(num)) {
continue
}
cache.add(num)
if (cache.has(num - k)) {
ans += 1
}
if (cache.has(num + k)) {
ans += 1
}
}
return ans
}