598. Range Addition II(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83096714

题目:

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 meansM[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: The range of m and n is [1,40000].
The range of a is [1,m], and the range of b is [1,n].
The range of operations size won’t exceed 10,000.

解释:
每次对于 0 <= i < a and 0 <= j < b范围内的数进行+1操作,求最终最大的数的个数。
暴力求解肯定是不可取的,可以知道的是最终最大的数字一定是集中在矩阵左上角的一个矩阵,最大的数字是每次操作都会+1的位置, 这些位置就是0 <=i<min_a and 0<=i<min_b,所以个数就是min_a * min_b

python代码:

class Solution(object):
    def maxCount(self, m, n, ops):
        """
        :type m: int
        :type n: int
        :type ops: List[List[int]]
        :rtype: int
        """
        if not ops:
            return m*n
        else:
            return min(op[0] for op in ops)*min(op[1] for op in ops)

c++代码:

class Solution {
public:
    int maxCount(int m, int n, vector<vector<int>>& ops) {
        if(ops.size()==0)
            return m*n;
        vector<int> ops1;
        vector<int> ops2;
        for (auto op:ops)
        {
            ops1.push_back(op[0]);
            ops2.push_back(op[1]);
        }
        return (*min_element(ops1.begin(),ops1.end()))*(*min_element(ops2.begin(),ops2.end()));
    }
};

总结:
写c++ 容器范围的时候,不要手抖写错了…不然容易报runtime error错

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83096714
今日推荐