我们将题目给出大小为 m \times n 的矩阵 grid 每一行从小到大排序,那么题目等价于每次删除矩阵的末尾列,得分为该列的最大值。那么最后的答案就是每一列的最大值之和。
代码
[sol1-Python3]
1 2 3 4 5
classSolution: defdeleteGreatestValue(self, grid: List[List[int]]) -> int: for i in grid: i.sort() returnsum([max(i) for i inzip(*grid)])
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { publicintdeleteGreatestValue(int[][] grid) { intm= grid.length, n = grid[0].length; for (inti=0; i < m; i++) { Arrays.sort(grid[i]); } intres=0; for (intj=0; j < n; j++) { intmx=0; for (inti=0; i < m; i++) { mx = Math.max(mx, grid[i][j]); } res += mx; } return res; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intdeleteGreatestValue(vector<vector<int>>& grid){ int m = grid.size(), n = grid[0].size(); for (int i = 0; i < m; i++) { sort(grid[i].begin(), grid[i].end()); } int res = 0; for (int j = 0; j < n; j++) { int mx = 0; for (int i = 0; i < m; i++) { mx = max(mx, grid[i][j]); } res += mx; } return res; } };
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassSolution { publicintDeleteGreatestValue(int[][] grid) { int m = grid.Length, n = grid[0].Length; for (int i = 0; i < m; i++) { Array.Sort(grid[i]); } int res = 0; for (int j = 0; j < n; j++) { int mx = 0; for (int i = 0; i < m; i++) { mx = Math.Max(mx, grid[i][j]); } res += mx; } return res; } }
funcdeleteGreatestValue(grid [][]int)int { m := len(grid) n := len(grid[0]) for i := 0; i < m; i++ { sort.Ints(grid[i]) } res := 0 for j := 0; j < n; j++ { mx := 0 for i := 0; i < m; i++ { mx = max(mx, grid[i][j]) } res += mx } return res }
funcmax(a, b int)int { if a > b { return a } return b }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var deleteGreatestValue = function(grid) { const m = grid.length, n = grid[0].length; for (let i = 0; i < m; i++) { grid[i].sort((a, b) => a - b); } let res = 0; for (let j = 0; j < n; j++) { let mx = 0; for (let i = 0; i < m; i++) { mx = Math.max(mx, grid[i][j]); } res += mx; } return res; };
intcmp(voidconst* a, voidconst* b) { return *(int*)a - *(int*)b; }
intdeleteGreatestValue(int** grid, int gridSize, int* gridColSize) { int m = gridSize, n = *gridColSize; for (int i = 0; i < m; ++i) { qsort(grid[i], n, 4U, cmp); } int res = 0; for (int j = 0; j < n; j++) { int mx = 0; for (int i = 0; i < m; ++i) { if (grid[i][j] > mx) { mx = grid[i][j]; } } res += mx; } return res; }
复杂度分析
时间复杂度:O(m \times n \times \log n),其中 m,n 分别为矩阵 grid 的行列数,对矩阵 grid 的每一行排序的时间复杂度为 n \times \log n,共有 m 行,所以总的时间复杂度为 O(m \times n \times \log n)。