[코테 풀이] Sort the Students by Their Kth Score

시내·2024년 6월 26일

Q_2545) Sort the Students by Their Kth Score

출처 : https://leetcode.com/problems/sort-the-students-by-their-kth-score/

There is a class with m students and n exams. You are given a 0-indexed m x n integer matrix score, where each row represents one student and score[i][j] denotes the score the ith student got in the jth exam. The matrix score contains distinct integers only.

You are also given an integer k. Sort the students (i.e., the rows of the matrix) by their scores in the kth (0-indexed) exam from the highest to the lowest.

Return the matrix after sorting it.

class Solution {
    public class Scores {
        int[] scoresOfStudents;
        int criteria;

        public Scores(int[] scoresOfStudents, int criteria) {
            this.scoresOfStudents = scoresOfStudents;
            this.criteria = criteria;
        }
    }

    public class sort implements Comparator<Scores> {

        @Override
        public int compare(Scores o1, Scores o2) {
            return o2.scoresOfStudents[o2.criteria] - o1.scoresOfStudents[o1.criteria];
        }
    }
    
    public int[][] sortTheStudents(int[][] score, int k) {
        int[][] answer = new int[score.length][score[0].length];
        ArrayList<Scores> scoresArrayList = new ArrayList<>();
        for (int i = 0; i < score.length; i++) {
            Scores s = new Scores(score[i], k);
            scoresArrayList.add(s);
        }
        Collections.sort(scoresArrayList, new sort());
        int ind = 0;
        for(Scores scores : scoresArrayList){
            answer[ind++] = scores.scoresOfStudents;
        }
        return answer;
    }
    
    
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글