Re: [闲聊] 每日leetcode

楼主: dont   2024-08-29 13:58:40
947. Most Stones Removed with Same Row or Column
## 思路
stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
分成两个group:
[0,0], [0,2], [2,0], [2,2] -> 删掉3个stone
[1,1]
用两个dict 记录每个row跟col最后看到的石头idx
如果在同一条线上已经有石头了, 就作union find
## Code
```python
class UnionFind:
def __init__(self, n):
self.root = list(range(n))
self.rank = [1] * n
def find(self, x):
if self.root[x] != x:
self.root[x] = self.find(self.root[x])
return self.root[x]
def union(self, x, y):
rx, ry = self.find(x), self.find(y)
if rx == ry:
return 0
if self.rank[rx] >= self.rank[ry]:
self.rank[rx] += self.rank[ry]
self.root[ry] = rx
else:
self.rank[ry] += self.rank[rx]
self.root[rx] = ry
return 1
class Solution:
def removeStones(self, stones: List[List[int]]) -> int:
n = len(stones)
uf = UnionFind(n)
seen_rows = defaultdict(int) # row -> idx
seen_cols = defaultdict(int) # col -> idx
res = 0
for idx, (r, c) in enumerate(stones):
if r in seen_rows:
res += uf.union(seen_rows[r], idx)
if c in seen_cols:
res += uf.union(seen_cols[c], idx)
seen_rows[r] = idx
seen_cols[c] = idx
return res
```

Links booklink

Contact Us: admin [ a t ] ucptt.com