LC.P2679[矩阵中的和]

方法一:暴力

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int matrixSum(int[][] nums) {
int ans = 0, m = nums.length, n = nums[0].length;
int[] score = new int[m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int maxIndex = 0;
for (int k = 0; k < n; ++k) {
if (nums[j][maxIndex] < nums[j][k]) {
maxIndex = k;
}
}
score[j] = nums[j][maxIndex];
nums[j][maxIndex] = -1;
}
int max = 0;
for (int s : score) {
if (max < s) max = s;
}
ans += max;
}
return ans;
}
}
  • 时间复杂度:$O(n^2m)$
  • 空间复杂度:$O(m)$

方法二:排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int matrixSum(int[][] nums){
int ans = 0, m = nums.length, n = nums[0].length;
for (int[] num : nums) {
Arrays.sort(num);
}
for (int j = 0; j < n; ++j) {
int max = 0;
for (int i = 0; i < m; ++i) {
max = Math.max(max, nums[i][j]);
}
ans += max;
}
return ans;
}
}
  • 时间复杂度:$O(mnlogn)$
  • 空间复杂度:$O(logn)$