947 Most Stones Removed with Same Row or Column
1. Question
On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.
Now, a _move _consists of removing a stone that shares a column or row with another stone on the grid.
What is the largest possible number of moves we can make?
Example 1:
Example 2:
Example 3:
Note:
1 <= stones.length <= 1000
0 <= stones[i][j] <10000
2. Implementation
(1) Union Find
思路: 题目给出石头所在的坐标,只要两个石头在同一行或者同一列,则可以将其中一个石头拿走,问最多可以拿走多少个石头。其实这里拿走石头其实就相当于将一个石头归并到另一个石头中,这很典型的union-find的题目,union的规则也很简单,只要两个石头在同一行或者同一列即可。最后最多能拿走的石头的数量等于原来石头数量减去union中cluster的数目。
3. Time & Space Complexity
时间复杂度O(n^2 * logn), union-find的过程需要O(logn),遍历输入数组,检查它们的行或列是否相同需要O(n^2)时间, 空间复杂度O(n)
Last updated
Was this helpful?