您的位置:首页 > 编程语言 > Python开发

python--leetcode598. Range Addition II

2017-12-08 21:05 399 查看
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.
题目比较明了,具体请看图比较好理解。
解题思路:我一开始觉得直接暴力解也很快的事,于是我写了这么一个代码:
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 count

s=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]]))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: