leetcode 598. Range Addition II ( Python )

387 阅读20分钟

描述

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:

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 的 m*n 的矩阵 M , 然后经过在 ops 中每一个操作下,在 M 相应的范围内都加一,最后计算最大值的数量,暴力算法就是根据题意进行无脑相加,但是细想之后就会发现每一个操作都是一个从 (0,0)位置扩展出的一个矩阵,只需要找到这些操作中的最小矩阵的范围就可以找到答案,时间复杂度为 O(N),空间复杂度为 O(1)。

解答

class Solution(object):
    def maxCount(self, m, n, ops):
        """
        :type m: int
        :type n: int
        :type ops: List[List[int]]
        :rtype: int
        """
        min_r = float("inf")
        min_c = float("inf")
        for o in ops:
            min_r = min(min_r,m,o[0])
            min_c = min(min_c,n,o[1])
        return m*n if min_r == float("inf") or float("inf")==min_c else min_r*min_c
                
                 	      
		

运行结果

Runtime: 52 ms, faster than 77.94% of Python online submissions for Range Addition II.
Memory Usage: 14.2 MB, less than 24.00% of Python online submissions for Range Addition II.

每日格言:人生最大遗憾莫过于错误坚持和轻易放弃

请作者喝吃蛋挞 支付宝

支付宝

微信

微信