LeetCode 题解工作台

根据第 K 场考试的分数排序

班里有 m 位学生,共计划组织 n 场考试。给你一个下标从 0 开始、大小为 m x n 的整数矩阵 score ,其中每一行对应一位学生,而 score[i][j] 表示第 i 位学生在第 j 场考试取得的分数。矩阵 score 包含的整数 互不相同 。 另给你一个整数 k 。请你按第 k 场考试…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·排序

bolt

答案摘要

我们直接将 按照第 列的分数从大到小排序,然后返回即可。 时间复杂度 $O(m \times \log m)$,空间复杂度 $O(\log m)$。其中 为 的行数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

班里有 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
lightbulb

解题思路

方法一:排序

我们直接将 score\textit{score} 按照第 kk 列的分数从大到小排序,然后返回即可。

时间复杂度 O(m×logm)O(m \times \log m),空间复杂度 O(logm)O(\log m)。其中 mmscore\textit{score} 的行数。

1
2
3
4
class Solution:
    def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]:
        return sorted(score, key=lambda x: -x[k])
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Will check if you can sort rows based on a specific column rather than the whole row.

  • question_mark

    Expect awareness of descending order priority and how to preserve row structure.

  • question_mark

    May ask about in-place vs auxiliary space trade-offs for large matrices.

warning

常见陷阱

外企场景
  • error

    Sorting the entire row instead of comparing only the kth element.

  • error

    Accidentally reversing the order, giving ascending results instead of descending.

  • error

    Using extra space unnecessarily when an in-place sort suffices for m x n matrix.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Sort students by multiple exam scores, using primary, secondary sorting keys.

  • arrow_right_alt

    Handle matrices with duplicate scores in the kth exam, requiring stable sorting.

  • arrow_right_alt

    Sort columns instead of rows to rank exams rather than students.

help

常见问题

外企场景

根据第 K 场考试的分数排序题解:数组·排序 | LeetCode #2545 中等