leetcode699. 掉落的方块

本文提供了一种解决LeetCode下落方块问题的方法,通过比较新加入的方块与已有方块来确定堆叠高度的最大值,并用简单的代码实现。此方案易于理解,适合初学者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
https://leetcode-cn.com/problems/falling-squares/submissions/
我的代码不快,但也不至于超时,但是容易理解
每个新的格子进来,与之前的格子进行比较,找到最大值
代码:

public List<Integer> fallingSquares(int[][] positions) {
    List<Integer> ans = new ArrayList<>();
    int len = positions.length;
    Map<int[], Integer> map = new HashMap<>();
    int anss = 0;
    for (int i = 0; i < len; i++) {
        anss = Math.max(getAns(positions[i], map),anss);
        ans.add(anss);
    }
    return ans;
}

//找到本正方形的最高点
private int getAns(int[] position, Map<int[], Integer> map) {
    int ans = position[1];
    int h = position[1];
    //格子的右边界
    position[1] = position[0] + position[1];
    Set<int[]> set = map.keySet();
    //因为发现有覆盖,旧的要删除,所以使用迭代器
    Iterator<int[]> iterator = set.iterator();
    while(iterator.hasNext()){
        int[] key = iterator.next();
        //判断新格子与旧格子的关系
        int point = getpoint(key, position);
        if (point == 0) {
            //没有交集就结束
            continue;
        }
        int v = map.get(key);
        if (point == 2) {
            iterator.remove();
        }
        ans = Math.max(v + h, ans);
    }
    map.put(position, ans);
    return ans;
}

private int getpoint(int[] key, int[] position) {
    //新的能覆盖旧的
    if (position[0] <= key[0] && position[1] >= key[1]) {
        return 2;
    }
    //新的和旧的没有交集
    if (position[0] >= key[1] || position[1] <= key[0]) {
        return 0;
    }
    //有交集
    return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值