zoukankan      html  css  js  c++  java
  • 求一个矩阵中最大的二维矩阵 【微软面试100题 第三十五题】

    题目要求:

      求一个矩阵中最大的二维矩阵(元素和最大).如:

      1  2  0  3  4

      2  3  4  5  1

      1  1  5  3  0

      中最大的是4  5

           5  3.

      要求:1)写出算法;2)分析时间复杂度;3)写出相关代码。

      参考资料:编程之美 2.15

    题目分析:

      从矩阵开头逐个求2*2矩阵的和,找出最大,时间复杂度O(M*N),M/N为行/列;

    代码实现:

    #include <iostream>
    
    using namespace std;
    
    const int M = 3;
    const int N = 5;
    
    int FindMaxMatrix(int a[][N],int &res_i,int &res_j);
    
    int main(void)
    {
        int res_i,res_j;
        int a[M][N] = {{1,2,0,3,4},{2,3,4,5,1},{1,2,5,3,0}};
        int max = FindMaxMatrix(a,res_i,res_j);
        cout << "The max matrix is:" << endl << a[res_i][res_j] << "  " ;
        cout << a[res_i][res_j+1] << endl<<a[res_i+1][res_j] << "  " << a[res_i+1][res_j+1] << endl;
        cout << "and the max sum is:" << max << endl;
        return 0;
    }
    int FindMaxMatrix(int a[][N],int &res_i,int &res_j)
    {
        int maxSum = INT_MIN,sum;
        for(int i=0;i<M-1;i++)
            for(int j=0;j<N-1;j++)
            {
                sum = a[i][j]+a[i+1][j]+a[i][j+1]+a[i+1][j+1];
                if(maxSum < sum)
                {
                    maxSum = sum;
                    res_i = i;
                    res_j = j;
                }
            }
        return maxSum;
    }
  • 相关阅读:
    topsort模板,poj 2585
    CUG2012年暑期ACM训练赛(单人赛)
    第一个QT, "hello linux"
    AOE网络,最长路关键路径的学习
    种类位置信息:geometry
    标准对话框:StandardDialogs
    最近整理的模板
    单调队列的学习
    118 ZOJ Monthly, July 2012
    离散化 + unique + lower_bound的学习,hdu4325
  • 原文地址:https://www.cnblogs.com/tractorman/p/4064274.html
Copyright © 2011-2022 走看看