Skip to content

Commit badd57b

Browse files
authored
Create 851-loud-and-rich.js
1 parent 3fbd239 commit badd57b

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

851-loud-and-rich.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {number[][]} richer
3+
* @param {number[]} quiet
4+
* @return {number[]}
5+
*/
6+
const loudAndRich = function(richer, quiet) {
7+
const hash = {}
8+
for(const [a, b] of richer) {
9+
if(hash[b] == null) hash[b] = []
10+
hash[b].push(a)
11+
}
12+
const n = quiet.length
13+
14+
const res = []
15+
for(let i = 0; i < n; i++) {
16+
dfs(i)
17+
}
18+
19+
return res
20+
21+
function dfs(i) {
22+
if(res[i] != null) return res[i]
23+
res[i] = i
24+
25+
const nxt = hash[i] || []
26+
for(const e of nxt) {
27+
if(quiet[dfs(e)] < quiet[res[i]]) res[i] = res[e]
28+
29+
}
30+
return res[i]
31+
}
32+
};

0 commit comments

Comments
 (0)