|
| 1 | +--- |
| 2 | +title: 2679.In the matrix and the harmony.md |
| 3 | +date: '2024.01.01 0:00' |
| 4 | +tags: |
| 5 | + - - Python |
| 6 | + - - answer |
| 7 | + - - Array |
| 8 | + - - matrix |
| 9 | + - - Sort |
| 10 | + - - simulation |
| 11 | + - - heap(Priority queue) |
| 12 | +abbrlink: '5277100' |
| 13 | +--- |
| 14 | + |
| 15 | +# topic: |
| 16 | + |
| 17 | +[2679.In the matrix and the harmony.md](https://leetcode.cn/problems/sum-in-a-matrix/) |
| 18 | + |
| 19 | +# Thought: |
| 20 | +**One -line** |
| 21 | +First of all, the meaning is to find the largest number of each sub -list,Thenpopgo out,Finally ask for peace。 |
| 22 | +The effect of traversing again and again is too bad,So I thought of using itzip一次性Traversal多个子Array。 |
| 23 | +于yes先对每个子ArraySort,Then usezipTraversal,Find the maximum。 |
| 24 | +for example: |
| 25 | +`nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]]` |
| 26 | +Sort后: |
| 27 | +`nums = [[1,2,7],[2,4,6],[3,5,6],[1,2,3]]` |
| 28 | +Then usezipTraversal得到: |
| 29 | +`[(1,2,3,1),(2,4,5,2),(7,6,6,3)]` |
| 30 | +Find the maximum: |
| 31 | +`[3,5,7]` |
| 32 | +Context: |
| 33 | +`15` |
| 34 | +# Code: |
| 35 | + |
| 36 | +```python |
| 37 | +class Solution: |
| 38 | + def matrixSum(self, nums: List[List[int]]) -> int: |
| 39 | + return sum(max(i) for i in \ |
| 40 | + zip(*(sorted(sublist) for sublist in nums))) |
| 41 | +``` |
| 42 | +### *The role and the rolezip()explain |
| 43 | +```python |
| 44 | +nums = [[1,2,7],[2,4,6],[3,5,6],[1,2,3]] |
| 45 | + |
| 46 | +for i in range(len(nums[1])): |
| 47 | + for j in range(len(nums)): |
| 48 | + print(nums[j][i]) |
| 49 | +# ans = 123124527663 |
| 50 | +num1 = [1,2,7] |
| 51 | +num2 = [2,4,6] |
| 52 | +num3 = [3,5,6] |
| 53 | +num4 = [1,2,3] |
| 54 | +``` |
| 55 | +`zip()`The function corresponds to one -to -one elements in multiple lists,Then return onezipObject,Can uselist()Function convert to list。 |
| 56 | +```python |
| 57 | +for i in zip(num1, num2, num3, num4): |
| 58 | + print(i) |
| 59 | +#(1, 2, 3, 1) |
| 60 | +#(2, 4, 5, 2) |
| 61 | +#(7, 6, 6, 3) |
| 62 | +``` |
| 63 | +`*nums`The role ispythonNot a pointer,InsteadnumsEach element in the parameter is passed into the function。I understand here as a list。 |
| 64 | +```python |
| 65 | + |
| 66 | +# Enumerate |
| 67 | +print(*nums) |
| 68 | +# [1, 2, 7] [2, 4, 6] [3, 5, 6] [1, 2, 3] |
| 69 | +``` |
| 70 | +`zip(*nums)`WillnumsEach element is passed in as a parameterzip()In the function,Then return onezipObject,Can uselist()Function convert to list。 |
| 71 | +`zip(*nums)`Equivalent to`zip(num1, num2, num3, num4)`,innum1, num2, num3, num4yesnumsElement。 |
| 72 | +```python |
| 73 | +for i in zip(*nums): |
| 74 | + print(i) |
| 75 | +# Equivalent |
| 76 | +#(1, 2, 3, 1) |
| 77 | +#(2, 4, 5, 2) |
| 78 | +#(7, 6, 6, 3) |
| 79 | +``` |
0 commit comments