1 minute read

Tags: ,

Sorting:Comparator

這題一整個 怪怪的兒~

class Checker implements Comparator<Player> {
  	// complete this method
	public int compare(Player a, Player b) {

        if (a.score == b.score) {
                return a.name.compareTo(b.name);
        }
        return b.score - a.score;
    }
}
  • 全部code
import java.util.*;

class Player {
	String name;
	int score;

	Player(String name, int score) {
		this.name = name;
		this.score = score;
	}
}

class Checker implements Comparator<Player> {
  	// complete this method
	public int compare(Player a, Player b) {

        if (a.score == b.score) {
                return a.name.compareTo(b.name);
        }
        return b.score - a.score;
    }
}


public 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);
        }
    }
}
# Enter your code here. Read input from STDIN. Print output to STDOUT
class Player:
    def __init__(self, name, score):
        self.name = name
        self.score = score
        
    def __repr__(self):
        return "{} {}".format(self.name , self.score)
        
    def comparator(a, b):
        
        if a.score == b.score:
            return -1 if a.name < b.name else 1

        return b.score - a.score