栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts [Medium]

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts [Medium]

class Solution {
    public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
        int preH = 0, preV = 0, maxH = 1, maxV = 1;
        Arrays.sort(horizontalCuts);
        Arrays.sort(verticalCuts);
        for (int hh : horizontalCuts) {
            maxH = Math.max(maxH, hh - preH);
            preH = hh;
        }
        maxH = Math.max(maxH, h - preH);
        for (int vv : verticalCuts) {
            maxV = Math.max(maxV, vv - preV);
            preV = vv;
        }
        maxV = Math.max(maxV, w - preV);
        return (int)((long)maxH * maxV % 1000000007);
    }
}

本来还想试下面这种方法,给每一个方向创建一个数组,遍历cut数组并在被cut的一行标记,再遍历标记后的数组,得到最长的连续cut长度,这样不需要排序

但是发现当h和w设置的很大的时候,会超出内存limit

确实大部分情况下cut的数量会比h、w要小很多,排序应该也不会消耗太多资源,反而是用这种方法占用了太多内存

class Solution {
    public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
        boolean[] hCuts = new boolean[h], vCuts = new boolean[w];
        int maxH = 0, maxV = 0, pre = 0;
        
        for (int cut : horizontalCuts) {
            hCuts[cut] = true;
        }
        for (int i = 1; i < hCuts.length; i++) {
            if (hCuts[i]) {
                maxH = Math.max(maxH, i - pre);
                pre = i;
            }
        }
        maxH = Math.max(maxH, h - pre);
        pre = 0;
        
        for (int cut : verticalCuts) {
            vCuts[cut] = true;
        }
        for (int i = 0; i < vCuts.length; i++) {
            if (vCuts[i]) {
                maxV = Math.max(maxV, i - pre);
                pre = i;
            }
        } 
        maxV = Math.max(maxV, w - pre);
        
        return (int)((long)maxH * maxV % 1000000007);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/306802.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号