LeetCode—947. 移除最多的同行或同列石头(Most Stones Removed with Same Row or Column)——分析及代码(Java)

LeetCode—947. 移除最多的同行或同列石头[Most Stones Removed with Same Row or Column]——分析及代码[Java]

一、题目

n 块石头放置在二维平面中的一些整数坐标点上。每个坐标点上最多只能有一块石头。
如果一块石头的 同行或者同列 上有其他石头存在,那么就可以移除这块石头。
给你一个长度为 n 的数组 stones ,其中 stones[i] = [xi, yi] 表示第 i 块石头的位置,返回 可以移除的石子 的最大数量。

示例 1:

输入:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
输出:5
解释:一种移除 5 块石头的方法如下所示:
1. 移除石头 [2,2] ,因为它和 [2,1] 同行。
2. 移除石头 [2,1] ,因为它和 [0,1] 同列。
3. 移除石头 [1,2] ,因为它和 [1,0] 同行。
4. 移除石头 [1,0] ,因为它和 [0,0] 同列。
5. 移除石头 [0,1] ,因为它和 [0,0] 同行。
石头 [0,0] 不能移除,因为它没有与另一块石头同行/列。

示例 2:

输入:stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
输出:3
解释:一种移除 3 块石头的方法如下所示:
1. 移除石头 [2,2] ,因为它和 [2,0] 同行。
2. 移除石头 [2,0] ,因为它和 [0,0] 同列。
3. 移除石头 [0,2] ,因为它和 [0,0] 同行。
石头 [0,0] 和 [1,1] 不能移除,因为它们没有与另一块石头同行/列。

示例 3:

输入:stones = [[0,0]]
输出:0
解释:[0,0] 是平面上唯一一块石头,所以不可以移除它。

提示:

  • 1 <= stones.length <= 1000
  • 0 <= xi, yi <= 104
  • 不会有两块石头放在同一个坐标点上

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/most-stones-removed-with-same-row-or-column
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、分析及代码

1. 并查集

(1)思路

将出现在同一行/列的石头计入同一连通分量,根据题意,每一连通分量最少只保留 1 块石头,进而可求得答案。
为简化过程,可将横、纵坐标用同一数组表示,其中 0 - 10000 表示横坐标,10001 - 20001 表示纵坐标,即可避免冲突。

(2)代码

class Solution {
    public int removeStones(int[][] stones) {
        int [] parent = new int[20002];//10001行,10001列
        Arrays.fill(parent, -1);
        for (int i = 0; i < stones.length; i++)
            union(parent, stones[i][0], stones[i][1] + 10001);
        int ans = stones.length;
        for (int i = 0; i < parent.length; i++)
            if (parent[i] == i)
                ans--;
        return ans;
    }

    public int find(int[] parent, int index) {
        if (parent[index] < 0)
            parent[index] = index;
        if (parent[index] != index)
            parent[index] = find(parent, parent[index]);
        return parent[index];
    }

    public void union(int[] parent, int index1, int index2) {
        parent[find(parent, index2)] = find(parent, index1);
    }
}

(3)结果

执行用时 :5 ms,在所有 Java 提交中击败了 98.01% 的用户;
内存消耗 :38.9 MB,在所有 Java 提交中击败了 29.44% 的用户。

三、其他

暂无。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值