-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution1.js
54 lines (48 loc) · 978 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/find-common-characters/
*
* 1002. Find Common Characters
*
* Easy
*/
const commonChars = A => {
const max = A.length
const ans = []
if (!max) {
return ans
}
let current = null
current = record(A[0])
for (let i = 1; i < A.length; i++) {
const temp = record(A[i])
current = intersection(current, temp)
}
for (let [key, value] of current) {
for (let i = 0; i < value; i++) {
ans.push(key)
}
}
return ans
}
function intersection (source, target) {
const result = new Map()
for (let [key, value] of target) {
const pre = source.get(key)
if (pre) {
const x = pre >= value ? value : pre
result.set(key, x)
}
}
return result
}
function record (s) {
const cache = new Map()
for (let i = 0; i < s.length; i++) {
const item = s[i]
if (!cache.get(item)) {
cache.set(item, 0)
}
cache.set(item, cache.get(item) + 1)
}
return cache
}