Created
November 26, 2018 20:07
-
-
Save jan25/b21d97549bf7c5c5454513e97e14569b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def removeStones(self, stones): | |
t = [-1] * len(stones) | |
xs, ys = {}, {} | |
for i, p in enumerate(stones): | |
x, y = p | |
if x in xs: self.onion(xs[x], i, t) | |
else: xs[x] = i | |
if y in ys: self.onion(ys[y], i, t) | |
else: ys[y] = i | |
return len(stones) - sum([1 for p in t if p < 0]) | |
def onion(self, a, b, t): | |
a, b = self.root(a, t), self.root(b, t) | |
if a == b: return | |
if t[a] > t[b]: a, b = b, a | |
t[b] = a | |
def root(self, a, t): | |
if t[a] < 0: return a | |
t[a] = self.root(t[a], t) | |
return t[a] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment