zoukankan      html  css  js  c++  java
  • 微软算法100题35 求一个矩阵中最大的二维矩阵

    35.
    求一个矩阵中最大的二维矩阵(元素和最大).如:
    1 2 0 3 4
    2 3 4 5 1
    1 1 5 3 0
    中最大的是:
    4 5
    5 3

    思路: 可以用一个2X2的二维矩阵从第一行开始依次遍历直到找到和是最大的那个子矩阵,但暴力破解一般都不是最优答案。 我的想法是如果用2X2矩阵逐行遍历的话,其实每次计算2X2矩阵的和的时候,其中的第一行其实在上次计算中已经算过了,如果计算的时候可以使用上次的结果,无疑可以改善性能,降低复杂度,所以应该将2X2矩阵的第一列缓存到变量里,每次移动窗口时,更新该变量

     1 package com.rui.microsoft;
     2 
     3 public class Test35_MaxSubMatrix {
     4 
     5     public static void main(String[] args) {
     6         int a[][] = {{1,2,0,3,4},{2,3,4,5,1},{1,1,5,3,0}};
     7         int res[][] = find(a, 3, 5);
     8         for(int i = 0; i < res.length; i++){
     9             for(int j = 0; j <res[0].length; j++){
    10                 System.out.print(" " + res[i][j]);
    11             }
    12             System.out.println("");
    13         }
    14     }
    15     
    16     public static int[][] find(int[][] matrix, int rows, int cols){
    17         int[][] res = new int[2][2];
    18         
    19         int max_i = 0;
    20         int max_j = 0;
    21         int max = Integer.MIN_VALUE;
    22         
    23         for(int i = 0; i < rows - 1; i++){
    24             int colSum = matrix[i][0] + matrix[i+1][0];
    25             for(int j = 1; j < cols; j++){
    26                 int matrixSum = colSum;
    27                 colSum = matrix[i][j] + matrix[i+1][j];
    28                 matrixSum += colSum;
    29                 
    30                 if(matrixSum > max){
    31                     max = matrixSum;
    32                     max_i = i;
    33                     max_j = j;
    34                 }
    35             }
    36         }
    37         
    38         System.out.println("max_i: " + max_i);
    39         System.out.println("max_j: " + max_j);
    40         
    41         res[0][0] = matrix[max_i][max_j-1];
    42         res[0][1] = matrix[max_i][max_j];
    43         res[1][0] = matrix[max_i+1][max_j - 1];
    44         res[1][1] = matrix[max_i+1][max_j];
    45         
    46         return res;
    47     }
    48 }
  • 相关阅读:
    暂存未看的网址
    学习springboot+shiro的实际应用demo
    mapper.xml 的配置
    使用idea搭建Spring boot+jsp的简单web项目
    一文读懂SpringCloud与Eureka,Feign,Ribbon,Hystrix,Zuul核心组件间的关系
    .net core mvc 类库读取配置文件
    .net Core 2.0应用程序发布到IIS上注意事项
    Dapper扩展
    C# 请求Https
    js 记录
  • 原文地址:https://www.cnblogs.com/aalex/p/4939664.html
Copyright © 2011-2022 走看看