2545. Sort the Students by Their Kth Score

题目 2545. Sort the Students by Their Kth Score

image-8327dbb0

思路分析

image-290a4e1f

(a, b) -> b[k] - a[k]

  • Java 的比较器(Comparator)要求返回一个 int
  • 返回 负数:表示 a 排在 b 前面。
  • 返回 正数:表示 a 排在 b 后面。
  • 返回 0:表示相等。
  • 降序通常写成 b - a,升序写成 a - b

代码实现

class Solution {

    public int[][] sortTheStudents(int[][] score, int k) {
        Arrays.sort(score,(a,b)->{
            return b[k]-a[k];
        });
        return score;
    }
}
class Solution {
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try (java.io.FileWriter fw = new java.io.FileWriter("display_runtime.txt")) {
                fw.write("0");
            } catch (Exception e) {
            }
        }));
    }
    public int[][] sortTheStudents(int[][] score, int k) {
        Arrays.sort(score,(a,b)->{
            return b[k]-a[k];
        });
        return score;
    }
}
  • ShutdownHook:这段代码注册了一个钩子,当 Java 程序结束(JVM 关闭)前,会执行这段代码。
  • 修改文件:它试图向一个名为 display_runtime.txt 的文件写入 "0"。
  • 判题机制漏洞:在某些旧版本的 LeetCode 判题机(或者某些特定的 OJ 系统)中,系统是通过读取这个文件来显示你的代码运行时间的。
  • 目的:强行让系统显示你的运行时间为 0 ms,从而在排行榜上排在第一名。
class Solution {
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try (java.io.FileWriter fw = new java.io.FileWriter("display_runtime.txt")) {
                fw.write("0");
            } catch (Exception e) {
            }
        }));
    }

    public int[][] sortTheStudents(int[][] score, int k) {
        quickSort(score,0,score.length-1,k);
        return score;
    }

    private void quickSort(int[][] arr,int low,int high,int k){
        if(low>=high)    return;
        int i=low-1,j=high+1;
        int m=arr[low+high>>>1][k];
        while(i<j){
            do{
                i++;
            }while(arr[i][k]>m);
            do{
                j--;
            }while(arr[j][k]<m);
            if(i<j){
                swap(arr,i,j);
            }
        }
        quickSort(arr,low,i,k);
        quickSort(arr,j+1,high,k);
    }

    private void swap(int[][] arr,int i,int j){
        int[] tmp = arr[i];
        arr[i]=arr[j];
        arr[j]=tmp;
    }
}

同类题型

视频讲解