• 《程序员代码面试指南》第一章 栈和队列 求最大子矩阵大小


    题目

    给定一个整形数组 map,其中值只有0和1两种,求所有全是1的所有子矩阵中,最大的矩阵全是1的数量
    

    java代码

    /**
     * @Description: 求最大子矩阵大小
     * @Author: lizhouwei
     * @CreateDate: 2018/4/6 0:12
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter1_9 {
        public int maxSubMatrixSize(int[][] map) {
            if (map == null) {
                return 0;
            }
            int[] height = new int[map[0].length];
            int maxSize = 0;
            for (int i = 0; i < map.length; i++) {
                //每一行中,子矩阵的高度
                for (int j = 0; j < map[0].length; j++) {
                    height[j] = map[i][j] == 0 ? 0 : height[j] + 1;
                }
                maxSize = Math.max(getMatrixMaxSize(height), maxSize);
            }
            return maxSize;
        }
    
        public int getMatrixMaxSize(int[] height) {
            if (height == null || height.length == 0) {
                return 0;
            }
            int maxSize = 0;
            Stack<Integer> stack = new Stack<Integer>();
            for (int i = 0; i < height.length; i++) {
                while (!stack.isEmpty() && height[i] <= height[stack.peek()]) {
                    int j = stack.pop();
                    int k = stack.isEmpty() ? -1 : stack.peek();
                    //例如: i=6,k =4 则 元素的边界为4到6,
                    maxSize = Math.max((i - k - 1) * height[j], maxSize);
                }
                stack.push(i);
            }
            //栈中可能还有未计算完的元素,此时height的长度作为元素的边界
            while (!stack.isEmpty()) {
                int j = stack.pop();
                int k = stack.isEmpty() ? -1 : stack.peek();
                maxSize = Math.max((height.length - k - 1) * height[j], maxSize);
            }
            return maxSize;
        }
    
        //测试
        public static void main(String[] args) {
            Chapter1_9 chapter = new Chapter1_9();
            int[][] arr = {{1, 0, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 0}};
            int res = chapter.maxSubMatrixSize(arr);
            System.out.print(res + "  ");
        }
    }
    
    
  • 相关阅读:
    Ansible自动部署lnmp架构+上线电商
    elastalert 基于EFK环境的邮件报警
    冒泡法、选择法、插入法排序
    Java的基本数据类型
    cmd运行java程序找不到或无法加载主类解决办法
    JavaBean进行表单开发
    Web项目各目录详解
    【数论】整数分块及详细证明
    题解 P4874 【[USACO14DEC] Piggyback_Silver 背负式运输(银)】
    题解 P3792 【由乃与大母神原型和偶像崇拜】
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8725883.html
Copyright © 2020-2023  润新知