반응형
1). 문제 : www.hackerrank.com/challenges/sherlock-and-anagrams/
2). 풀이 :
Comparator를 알고있는지 모르는지에 대한 문제였던것 같다.
compareTo를 사용했을때 클때, 같을때 작을때 1, 0, -1 을 return하는것만 알고있으면 비교할때 쉬울수있는 문제.
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) {
int result = 0;
if(a.score<b.score){
result = 1;
}else if(a.score>b.score){
result = -1;
}else{
return a.name.compareTo(b.name);
}
return result;
}
}
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);
}
}
}
반응형
'Java > Algorithm' 카테고리의 다른 글
[Java-Algorithm] HackerRank Java - Minimum Absolute Difference in an Array 풀이 (0) | 2021.02.08 |
---|---|
[Java-Algorithm] HackerRank Java - Sherlock and the Valid String 풀이 (0) | 2021.02.01 |
[Java-Algorithm] HackerRank Java - Two Strings 풀이 (0) | 2021.01.29 |
[Java-Algorithm] HackerRank Java - Hash Tables: Ransom Note 풀이 (0) | 2021.01.29 |
[Java-Algorithm] HackerRank Java - Array Manipulation -누적합풀이 (0) | 2021.01.27 |