python--leetcode598. Range Addition II
来源:互联网 发布:衣服软件 编辑:程序博客网 时间:2024/06/11 17:54
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 = 3operations = [[2,2],[3,3]]Output: 4Explanation: 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.
题目比较明了,具体请看图比较好理解。
解题思路:我一开始觉得直接暴力解也很快的事,于是我写了这么一个代码:
class Solution(object): def maxCount(self, m, n, ops): """ :type m: int :type n: int :type ops: List[List[int]] :rtype: int """ a=[ [0 for i in range(m)] for j in range(n)] for i in range(len(ops)): x,y=ops[i][0],ops[i][1] for j in range(m): for k in range(n): if j<x and k<y: a[j][k]+=1 max,count=0,0 for j in range(m): for k in range(n): if(max<a[j][k]):max=a[j][k] for j in range(m): for k in range(n): if (max == a[j][k]):count+=1 return counts=Solution()print(s.maxCount(4000,4000,[]))是不是看上去很清新脱俗?而且思路很清晰,感觉分分钟就解决了这题。其实这样的话会严重超时。
后来我又想了一想,发现这一题只要把list中最小的x和y找出来,他们的乘积就是最后的结果了,同学们可以仔细想一想是不是这么一回事。
因为最小的x和y这块区域,只要有+1,这块区域就一定加一,所以他们的数字一定是最大的。
代码如下:
class Solution(object): def maxCount(self, m, n, ops): """ :type m: int :type n: int :type ops: List[List[int]] :rtype: int """ if(len(ops)==0): return m*n x,y=[],[] for i in range(len(ops)): x.append(ops[i][0]) y.append(ops[i][1]) return min(x)*min(y)s=Solution()print(s.maxCount(3,3,[[2,2],[3,3]]))
阅读全文
1 0
- python--leetcode598. Range Addition II
- leetcode598. Range Addition II
- leetcode598. Range Addition II降维
- 598. Range Addition II
- 598. Range Addition II
- 598. Range Addition II
- 598. Range Addition II
- 598. Range Addition II
- 598. Range Addition II
- 598. Range Addition II
- 598. Range Addition II
- 598. Range Addition II
- leetcode[Range Addition II]
- 598. Range Addition II
- 598. Range Addition II
- Range Addition II(leetcode)
- [leetcode]598. Range Addition II
- [leetcode]: 598. Range Addition II
- LeetCode-016 3Sum Closest
- 基于ZooKeeper的分布式锁
- 7-类的加载、连接、初始化
- TCP/IP详解学习笔记(1)-基本概念
- Python实现Pat 1034. Head of a Gang (30)
- python--leetcode598. Range Addition II
- oracle数据库sql语句06 join
- tensorflow系列1:两种方式优化损失函数
- MySQL的CURD
- PAT1041. 考试座位号(15) C++
- oracle数据库sql语句07 PL SQL程序结构
- oracle数据库sql语句08 PL SQL程序结构 循环 游标
- 第一章 基础知识
- oracle数据库sql语句09 PL SQL程序结构 异常