-
[hackerRank] JavaComparator알고리즘 2021. 2. 25. 22:27
문제
www.hackerrank.com/challenges/java-comparator/problem
접근방법
- 점수 내림차순 + 동점시 이름 알파벳순으로 구현하면됨
- 단순 기본 정렬이라면, compareable을 사용해도되지만, 위와 같은 복합적인 조건이라면 comparetor를 구현하면 된다
package com.cm; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; /** * https://www.hackerrank.com/challenges/java-comparator/problem */ public class JavaComparator { class Checker implements Comparator<Player>{ @Override public int compare(Player o1, Player o2) { if(o1.score > o2.score){ return -1; // 내림차순 }else if(o1.score < o2.score){ return 1; }else if (o1.score == o2.score){ // 알파벳순 return o1.name.compareTo(o2.name); } return 0; } } class Player{ String name; int score; Player(String name, int score){ this.name = name; this.score = score; } } public JavaComparator() { solution(); } public void solution(){ 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); } } } //CLASS END
'알고리즘' 카테고리의 다른 글
[hackerRank] primChecker (0) 2021.02.28 [hackerRank] JAVA Stack (0) 2020.10.26 [hackerRank] StringReverse (0) 2020.10.06 [hackerRank] datatypes (0) 2020.09.29 [hackerRank] AppleAndOrange (0) 2019.12.17