两种方法:
第一种:先对二维列表的每一列进行排序,然后对每一列的数据进行逐个比较,找出最大值。
class Solution:
def matrixSum(self, nums: list[list[int]]) -> int:
result=0
m=len(nums)
n=len(nums[0])
for i in range(m):
nums[i].sort()
for j in range(n):
max_1 = 0
for i in range(m):
max_1 = max(max_1,nums[i][j])
result+=max_1
return result
nums = Solution()
print(nums.matrixSum([[7,2,1],[6,4,2],[6,5,3],[3,2,1]]))
第二种:先对二维列表每行进行排序,后利用python的内置函数zip进行计算(时间复杂度底)
zip函数详细用法请看菜鸟教程:Python zip() 函数 | 菜鸟教程 (runoob.com)
class Solution:
def matrixSum(self, nums: List[List[int]]) -> int:
for row in nums:
row.sort()
result = 0
for col in zip(*nums):
result += max(col)
return result
nums = Solution()
print(nums.matrixSum([[7,2,1],[6,4,2],[6,5,3],[3,2,1]]))