Skip to content

Commit 44add54

Browse files
authored
Create most-stones-removed-with-same-row-or-column.cpp
1 parent 926b996 commit 44add54

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int removeStones(vector<vector<int>>& stones) {
7+
static const int MAX_ROW = 10000;
8+
UnionFind union_find(2 * MAX_ROW);
9+
for (const auto& stone : stones) {
10+
union_find.union_set(stone[0], stone[1] + MAX_ROW);
11+
}
12+
unordered_set<int> components;
13+
for (const auto& stone : stones) {
14+
components.emplace(union_find.find_set(stone[0]));
15+
}
16+
return stones.size() - components.size();
17+
}
18+
19+
private:
20+
class UnionFind {
21+
public:
22+
UnionFind(const int n) : set_(n) {
23+
iota(set_.begin(), set_.end(), 0);
24+
}
25+
26+
int find_set(const int x) {
27+
if (set_[x] != x) {
28+
set_[x] = find_set(set_[x]); // Path compression.
29+
}
30+
return set_[x];
31+
}
32+
33+
void union_set(const int x, const int y) {
34+
int x_root = find_set(x), y_root = find_set(y);
35+
if (x_root != y_root) {
36+
set_[min(x_root, y_root)] = max(x_root, y_root);
37+
}
38+
}
39+
40+
private:
41+
vector<int> set_;
42+
};
43+
};

0 commit comments

Comments
 (0)