1. 내 풀이
gpt의 도움을 받아 작성했다.
Double.compare(), Integer.compare() 함수를 활용할 수 있게 되었다.
import java.util.*;
class Solution {
public int[] solution(int N, int[] stages) {
int[] stageCount = new int[N + 2];
int challengedNumber = stages.length;
for (int stage : stages) {
stageCount[stage]++;
}
Map<Integer, Double> failureRateMap = new HashMap<>();
for (int i = 1; i <= N; i++) {
if (challengedNumber == 0) {
failureRateMap.put(i, 0.0);
} else {
failureRateMap.put(i, (double) stageCount[i] / challengedNumber);
challengedNumber -= stageCount[i];
}
}
List<Integer> sortedStages = new ArrayList<>(failureRateMap.keySet());
sortedStages.sort((a, b) -> {
int compare = Double.compare(failureRateMap.get(b), failureRateMap.get(a));
return compare == 0 ? Integer.compare(a, b) : compare;
});
return sortedStages.stream().mapToInt(i -> i).toArray();
}
}
collections.sort vs list.sort
✅ Java 7 스타일 (Collections.sort())
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5); Collections.sort(numbers, (a, b) -> a - b);
✅ Java 8 스타일 (List.sort()) -> 가독성 좋고 성능이 약간 더 향상됨 : 이걸 사용하기!
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5); numbers.sort((a, b) -> a - b);
2. 다른 분 풀이
클래스를 새로 정의해서 풀었다. 새로 클래스 정의하기 귀찮아서 나는 이렇게 안했는데,, 다음엔 이런 방법도 도전해봐야겠다.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
public int[] solution(int N, int[] lastStages) {
int nPlayers = lastStages.length;
int[] nStagePlayers = new int[N + 2];
for (int stage : lastStages) {
nStagePlayers[stage] += 1;
}
int remainingPlayers = nPlayers;
List<Stage> stages = new ArrayList<>();
for (int id = 1 ; id <= N; id++) {
double failure = (double) nStagePlayers[id] / remainingPlayers;
remainingPlayers -= nStagePlayers[id];
Stage s = new Stage(id, failure);
stages.add(s);
}
Collections.sort(stages, Collections.reverseOrder());
int[] answer = new int[N];
for (int i = 0; i < N; i++) {
answer[i] = stages.get(i).id;
}
return answer;
}
class Stage implements Comparable<Stage> {
public int id;
public double failure;
public Stage(int id_, double failure_) {
id = id_;
failure = failure_;
}
@Override
public int compareTo(Stage o) {
if (failure < o.failure ) {
return -1;
}
if (failure > o.failure ) {
return 1;
}
return 0;
}
}
}
'코딩테스트 > Programmers' 카테고리의 다른 글
[프로그래머스] 다트 게임 (0) | 2025.03.05 |
---|---|
[프로그래머스] 옹알이(2) (0) | 2025.03.05 |
[프로그래머스] 소수 찾기 (0) | 2025.03.05 |
[프로그래머스] 기사단원의 무기 (1) | 2025.03.02 |
[프로그래머스] 포켓몬 (0) | 2025.03.01 |