Skip to content

Commit 52ba9fc

Browse files
committed
851
1 parent 0a47b12 commit 52ba9fc

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

DFS/traditionalDFS/851.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
## Loud and Rich
2+
3+
#### Description
4+
5+
[link](https://leetcode.com/problems/loud-and-rich/)
6+
7+
---
8+
9+
#### Solution
10+
11+
- See Code
12+
13+
---
14+
15+
#### Code
16+
17+
> 最坏情况:O(n^2)
18+
19+
```python
20+
class Solution:
21+
'''
22+
思路:
23+
1. 设定所谓的dfs是返回一个值,这个值代表着dfs当前person的结果,也就是满足条件的最小
24+
quiet的人
25+
2. 事先设定一个对应的res数组,将初始值设置为负数
26+
3. 当我们在dfs过程中只要遇到了res的值大于等于0则必然已经经历过dfs,直接更新答案即可
27+
4. 默认更新res为i,同时在比i大的任意j中进行dfs,寻找他们的满足条件的答案
28+
5. 由于答案每次都被更新,所以必然可以保证不出现重复计算,效率最高
29+
6. 此题的难度在于必须要进一步更新所有比i大的数字,而不是只是一层即可
30+
'''
31+
def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
32+
m = collections.defaultdict(list)
33+
for i, j in richer: m[j].append(i)
34+
res = [-1] * len(quiet)
35+
36+
def dfs(i):
37+
if res[i] >= 0: return res[i]
38+
res[i] = i
39+
for j in m[i]:
40+
if quiet[res[i]] > quiet[dfs(j)]: res[i] = res[j]
41+
return res[i]
42+
43+
for i in range(len(quiet)): dfs(i)
44+
return res
45+
```

0 commit comments

Comments
 (0)