【LetMeFly】2545.根据第 K 场考试的分数排序:考察编程语言的排序
力扣题目链接:https://leetcode.cn/problems/sort-the-students-by-their-kth-score/
班里有 m
位学生,共计划组织 n
场考试。给你一个下标从 0 开始、大小为 m x n
的整数矩阵 score
,其中每一行对应一位学生,而 score[i][j]
表示第 i
位学生在第 j
场考试取得的分数。矩阵 score
包含的整数 互不相同 。
另给你一个整数 k
。请你按第 k
场考试分数从高到低完成对这些学生(矩阵中的行)的排序。
返回排序后的矩阵。
示例 1:
输入:score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2 输出:[[7,5,11,2],[10,6,9,1],[4,8,3,15]] 解释:在上图中,S 表示学生,E 表示考试。 - 下标为 1 的学生在第 2 场考试取得的分数为 11 ,这是考试的最高分,所以 TA 需要排在第一。 - 下标为 0 的学生在第 2 场考试取得的分数为 9 ,这是考试的第二高分,所以 TA 需要排在第二。 - 下标为 2 的学生在第 2 场考试取得的分数为 3 ,这是考试的最低分,所以 TA 需要排在第三。
示例 2:
输入:score = [[3,4],[5,6]], k = 0 输出:[[5,6],[3,4]] 解释:在上图中,S 表示学生,E 表示考试。 - 下标为 1 的学生在第 0 场考试取得的分数为 5 ,这是考试的最高分,所以 TA 需要排在第一。 - 下标为 0 的学生在第 0 场考试取得的分数为 3 ,这是考试的最低分,所以 TA 需要排在第二。
提示:
m == score.length
n == score[i].length
1 <= m, n <= 250
1 <= score[i][j] <= 105
score
由 不同 的整数组成0 <= k < n
解题方法:自定义排序
在各种编程语言中,调用排序函数(如有)对数组按照每一行下标 k k k从大到小的顺序排序。
- 时间复杂度 O ( m log m ) O(m\log m) O(mlogm)
- 空间复杂度 O ( log m ) O(\log m) O(logm)
AC代码
C++
/** @Author: LetMeFly* @Date: 2024-12-21 17:49:59* @LastEditors: LetMeFly.xyz* @LastEditTime: 2024-12-21 17:53:37* @Description: 没有全程在写*/
class Solution {
public:vector<vector<int>> sortTheStudents(vector<vector<int>>& score, int k) {sort(score.begin(), score.end(), [&k](const vector<int>& a, const vector<int>& b) {return a[k] > b[k];});return score;}
};
Python
'''
Author: LetMeFly
Date: 2024-12-21 17:55:19
LastEditors: LetMeFly.xyz
LastEditTime: 2024-12-21 17:56:05
'''
from typing import Listclass Solution:def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]:return sorted(score, key=lambda a: -a[k])
Java
/** @Author: LetMeFly* @Date: 2024-12-21 18:01:15* @LastEditors: LetMeFly.xyz* @LastEditTime: 2024-12-21 18:04:28*/
import java.util.Arrays;class Solution {public int[][] sortTheStudents(int[][] score, int k) {Arrays.sort(score, (a, b) -> b[k] - a[k]);return score;}
}
Go
/** @Author: LetMeFly* @Date: 2024-12-21 20:26:42* @LastEditors: LetMeFly.xyz* @LastEditTime: 2024-12-21 20:31:21*/
package mainimport "sort"func sortTheStudents(score [][]int, k int) [][]int {sort.Slice(score, func(i, j int) bool {return score[i][k] > score[j][k]})return score
}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/144635776