HR자바 Java Comparator

개요[ | ]

HR자바 Java Comparator
해커랭크 Java
# 문제 비고
HR자바 Data Structures e
28 HR자바 Java 1D Array
29 HR자바 Java 2D Array
30 HR자바 Java Subarray
31 HR자바 Java Arraylist
32 HR자바 Java 1D Array (Part 2)
33 HR자바 Java List
34 HR자바 Java Map
35 HR자바 Java Stack
36 HR자바 Java Hashset
37 HR자바 Java Generics
38 HR자바 Java Comparator
39 HR자바 Java Sort
40 HR자바 Java Dequeue
41 HR자바 Java BitSet
42 HR자바 Java Priority Queue

상단
import java.util.*;
구현예시 1
// Write your Checker class here
class Checker implements Comparator<Player> {
    public int compare(Player p1, Player p2) {
        if (p1.score != p2.score) {
            return p2.score - p1.score;
        }
        return p1.name.compareTo(p2.name);
    }
}
구현예시 2
// Write your Checker class here
class Checker implements Comparator {
    public int compare(Object o1, Object o2) {
        Player p1 = (Player) o1;
        Player p2 = (Player) o2;
        if (p1.score == p2.score) {
            return p1.name.compareTo(p2.name);
        }
        return p2.score - p1.score;
    }
}
하단
class Player{
    String name;
    int score;
    
    Player(String name, int score){
        this.name = name;
        this.score = score;
    }
}

class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        Player[] player = new Player[n];
        Checker checker = new Checker();
        
        for(int i = 0; i < n; i++){
            player[i] = new Player(scan.next(), scan.nextInt());
        }
        scan.close();

        Arrays.sort(player, checker);
        for(int i = 0; i < player.length; i++){
            System.out.printf("%s %s\n", player[i].name, player[i].score);
        }
    }
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}