997. 找到小鎮的法官
https://leetcode-cn.com/problems/find-the-town-judge/
在一個小鎮裏,按從 1 到 N 標記了 N 個人。傳言稱,這些人中有一個是小鎮上的祕密法官。如果小鎮的法官真的存在,那麼:
- 小鎮的法官不相信任何人。
- 每個人(除了小鎮法官外)都信任小鎮的法官。
- 只有一個人同時滿足屬性 1 和屬性 2 。
給定數組 trust,該數組由信任對 trust[i] = [a, b] 組成,表示標記爲 a 的人信任標記爲 b 的人。如果小鎮存在祕密法官並且可以確定他的身份,請返回該法官的標記。否則,返回 -1。
提示:
- 1 <= N <= 1000
- trust.length <= 10000
- trust[i] 是完全不同的
- trust[i][0] != trust[i][1]
- 1 <= trust[i][0], trust[i][1] <= N
題解
一:這是一道有向圖問題。 並且法官實際上就是出度爲0,入度爲 N - 1的節點。因此一個思路就是統計所有人的入度和出度信息,將滿足出度爲0,入度爲 N - 1的節點輸出。這裏用兩個數組 in_degree 和 out_degree 分別記錄入度和出度的信息,爲了簡單起見,我們初始化的數組長度爲 N + 1,而不是 N。
class Solution(object):
def findJudge(self, N, trust):
"""
:type N: int
:type trust: List[List[int]]
:rtype: int
"""
# out_degree信任別人,in_degree被別人信任
out_degree = [0 for _ in range(N + 1)]
in_degree = [0 for _ in range(N + 1)]
for pair in trust:
# pair[0] 信任別人
out_degree[pair[0]] += 1
# pair[1]被信任
in_degree[pair[1]] += 1
for i in range(1, N + 1):
if out_degree[i] == 0 and in_degree[i] == N - 1:
return i
return -1
1042. 不鄰接植花
https://leetcode-cn.com/problems/flower-planting-with-no-adjacent/
有 N 個花園,按從 1 到 N 標記。在每個花園中,你打算種下四種花之一。paths[i] = [x, y] 描述了花園 x 到花園 y 的雙向路徑。另外,沒有花園有 3 條以上的路徑可以進入或者離開。你需要爲每個花園選擇一種花,使得通過路徑相連的任何兩個花園中的花的種類互不相同。以數組形式返回選擇的方案作爲答案 answer,其中 answer[i] 爲在第 (i+1) 個花園中種植的花的種類。花的種類用 1, 2, 3, 4 表示。保證存在答案。
提示:
1 <= N <= 10000
0 <= paths.size <= 20000
- 不存在花園有 4 條或者更多路徑可以進入或離開。
- 保證存在答案。
題解
一:用鄰接表數組構造無向圖,假設初始時每個花園都是0號花,然後按1到N(0到N-1)的順序給每個花園種花。對每個花園,都有1、2、3、4四種花可選,用used_color數組標記每種花是否被與當前花園相通的鄰接花園使用過,標記完後,從剩餘的沒被使用過的花中選取號數最小的花種在當前花園。直至對所有花園完成種植。
class Solution(object):
def gardenNoAdj(self, N, paths):
"""
:type N: int
:type paths: List[List[int]]
:rtype: List[int]
"""
graph = [[] for _ in range(N)]
for path in paths:
graph[path[0] - 1].append(path[1] - 1)
graph[path[1] - 1].append(path[0] - 1)
res = [0 for _ in range(N)]
for i in range(N):
used_color = [False] * 5
for item in graph[i]:
if item < i:
used_color[res[item]] = True
for j in range(1, 5):
if not used_color[j]:
res[i] = j
break
return res