[LeetCode] 2679. Sum in a Matrix

发布时间 2023-07-05 08:05:15作者: CNoodle

You are given a 0-indexed 2D integer array nums. Initially, your score is 0. Perform the following operations until the matrix becomes empty:

  1. From each row in the matrix, select the largest number and remove it. In the case of a tie, it does not matter which number is chosen.
  2. Identify the highest number amongst all those removed in step 1. Add that number to your score.

Return the final score.

Example 1:

Input: nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]]
Output: 15
Explanation: In the first operation, we remove 7, 6, 6, and 3. We then add 7 to our score. Next, we remove 2, 4, 5, and 2. We add 5 to our score. Lastly, we remove 1, 2, 3, and 1. We add 3 to our score. Thus, our final score is 7 + 5 + 3 = 15.

Example 2:

Input: nums = [[1]]
Output: 1
Explanation: We remove 1 and add it to the answer. We return 1.

Constraints:

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

矩阵中的和。

给你一个下标从 0 开始的二维整数数组 nums 。一开始你的分数为 0 。你需要执行以下操作直到矩阵变为空:

矩阵中每一行选取最大的一个数,并删除它。如果一行中有多个最大的数,选择任意一个并删除。
在步骤 1 删除的所有数字中找到最大的一个数字,将它添加到你的 分数 中。
请你返回最后的 分数 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sum-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是排序。设矩阵有 m 行,每行有 n 列。我们将这 m 行排序,之后用一个指针 index 指向每一行同一个位置的元素,挑出这 m 个元素里最大的,将这个值累加到结果里。

时间O(m * nlogn)

空间O(1)

Java实现

 1 class Solution {
 2     public int matrixSum(int[][] nums) {
 3         int res = 0;
 4         int m = nums.length;
 5         int n = nums[0].length;
 6         for (int i = 0; i < m; i++) {
 7             int[] row = nums[i];
 8             Arrays.sort(row);
 9         }
10         
11         int index = n - 1;
12         while (index >= 0) {
13             int max = Integer.MIN_VALUE;
14             for (int i = 0; i < m; i++) {
15                 max = Math.max(max, nums[i][index]);
16             }
17             res += max;
18             index--;
19         }
20         return res;
21     }
22 }

 

LeetCode 题目总结