2023-07-04 LeetCode daily question (sum in matrix)

2023-07-04 one question per day

1. Topic number

2679. 矩阵中的和

2. Topic link

Click to jump to the topic location

3. Topic description

You are given a two-dimensional integer array nums whose subscripts start at 0 . At the beginning your score is 0. You need to do the following until the matrix becomes empty:

  1. Select the largest number for each row in the matrix and delete it. If there are multiple largest numbers in a row, select any one and delete it.
  2. Find the largest number among all the numbers removed in step 1 and add it to your score .

Please return your final score .

hint:

  • 1 <= nums.length <= 300
  • 1 <= nums[i].length <= 500
  • 0 <= nums[i][j] <= 103

4. Problem solving code

class Solution {
    
    
public:
    int matrixSum(vector<vector<int>>& nums) {
    
    
        int m = nums.size();
        int n = nums[0].size();
        int sum = 0;
       
        for(int i = 0; i < m; ++i){
    
    
            sort(nums[i].begin(), nums[i].end(), greater<int>());
        }
       
        for(int j = 0; j < n; ++j){
    
    
            int max0 = -1;
            for(int i = 0; i < m; ++i){
    
    
                max0 = max(max0, nums[i][j]);
            }
            sum += max0;
        }
        
    return sum;
    }
};
class Solution:
    def matrixSum(self, nums: List[List[int]]) -> int:
        res = 0
        m = len(nums)
        n = len(nums[0])
        for i in range(m):
            nums[i].sort()
        for j in range(n):
            max_val = 0
            for i in range(m):
                max_val = max(max_val, nums[i][j])
            res += max_val
        return res

Five, problem-solving ideas

(1) First of all, the requirement in the title is, <1> Find the maximum value of each row, and then delete the maximum value. <2> Find the largest number among these deleted numbers.

(2) We remember that nums.size() is equal to m, and nums[0].size() is equal to n. So the first thing we need to do is to use the sort function that comes with cpp to sort each row of the matrix from large to small .

(3) Then let's think about it, the maximum value found every time is in one column. That's because after sorting, the numbers have been sorted from largest to smallest.

(4) Then we traverse the n columns from left to right, and these n columns correspond to the corresponding numbers that we want to delete n times. Next, we use linear enumeration to find the largest number in each column, then the largest number in each column can be added to the total score of our results.

Guess you like

Origin blog.csdn.net/qq_56086076/article/details/131526886