zoukankan      html  css  js  c++  java
  • leetcode-598-Range Addition II

    题目描述:

    Given an m * n matrix M initialized with all 0's and several update operations.

    Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b.

    You need to count and return the number of maximum integers in the matrix after performing all the operations.

    Example 1:

    Input: 
    m = 3, n = 3
    operations = [[2,2],[3,3]]
    Output: 4
    Explanation: 
    Initially, M = 
    [[0, 0, 0],
     [0, 0, 0],
     [0, 0, 0]]
    
    After performing [2,2], M = 
    [[1, 1, 0],
     [1, 1, 0],
     [0, 0, 0]]
    
    After performing [3,3], M = 
    [[2, 2, 1],
     [2, 2, 1],
     [1, 1, 1]]
    
    So the maximum integer in M is 2, and there are four of it in M. So return 4.
    

     

    Note:

    1. The range of m and n is [1,40000].
    2. The range of a is [1,m], and the range of b is [1,n].
    3. The range of operations size won't exceed 10,000.

     

    要完成的函数:

    int maxCount(int m, int n, vector<vector<int>>& ops) 

    说明:

    1、这道题给定一个m行n列的矩阵,矩阵所有数值都是0。

    还给定了操作,放在二维矩阵中,比如[[2,2],[3,3]]这种形式,代表两个操作。

    第一个操作是对0<=i<2和0<=j<2的子矩阵所有元素都加1。矩阵变化为[[1,1,0],[1,1,0],[0,0,0]]。

    第二个操作是对0<=i<3和0<=j<3的子矩阵所有元素都加1。矩阵变化为[[2,2,1],[2,2,1],[1,1,1]]。

    最后返回矩阵中数值最大的元素有几个,上述矩阵数值最大为2,一共有4个,返回4,。

    2、上述题目似乎要对矩阵进行一个又一个的操作,最后再进行统计。

    但我们也可以不改变矩阵数值,直接返回最后有多少个最大数值的矩阵元素就好。矩阵初始化为0为我们提供了这样做的可能性。

    我们只需统计出所有这些操作都改变了哪些元素,哪些元素在每一次操作中都会加1。

    最后返回这些元素的个数就好了。

    代码如下:

        int maxCount(int m, int n, vector<vector<int>>& ops) 
        {
            int s1=ops.size();
            if(s1==0)//边界情况,操作的矩阵是空的
                return m*n;
            int a=ops[0][0],b=ops[0][1];
            for(int i=1;i<s1;i++)//统计出所有操作都改变了前几行,都改变了前几列
            {
                a=min(a,ops[i][0]);
                b=min(b,ops[i][1]);
            }
            return a*b;//最后返回改变的行数*列数
        }
    

    上述代码实测9ms,beats 99.52% of cpp submissions。

  • 相关阅读:
    常用的知识点
    2021年度“新时代好少年”
    音频格式TDM
    DTS
    学习总结之EXTJS相关了解和问题解决篇
    java中extends和implements的区别
    开发
    程序员练级(转自酷壳)
    优秀程序员无它善假于物也
    EXTJS开发过程遇到的一些问题的小结(转自麦田守望者)
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9159515.html
Copyright © 2011-2022 走看看