문제 링크
실패율
풀이
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.stream.Stream;
class Solution {
public static Integer[] solution(int N, int[] stages) {
HashMap<Integer, Integer> stageSurvivor = new HashMap<>();
HashSet<FailRate> failRateSet = new HashSet<>();
for (int i = 0; i < stages.length; i++) {
if (stageSurvivor.containsKey(stages[i])) {
stageSurvivor.put(stages[i], stageSurvivor.get(stages[i]) + 1);
} else {
stageSurvivor.put(stages[i], 1);
}
}
int person = stages.length;
for (int i = 1; i < N + 1; i++) {
if (stageSurvivor.containsKey(i)) {
double failRate = (double) stageSurvivor.get(i) / person;
person -= stageSurvivor.get(i);
failRateSet.add(new FailRate(i, failRate));
} else {
failRateSet.add(new FailRate(i, 0d));
}
}
Stream<FailRate> sortedByStreamCompare = failRateSet.stream().sorted(Comparator.comparing(FailRate::getFailRate, Comparator.reverseOrder()).thenComparing(FailRate::getStage));
Integer[] answer = sortedByStreamCompare.map(x -> x.stage).toArray(Integer[]::new);
return answer;
}
}
class FailRate {
int stage;
double failRate;
public FailRate(int stage, double failRate) {
this.stage = stage;
this.failRate = failRate;
}
public int getStage() {
return stage;
}
public void setStage(int stage) {
this.stage = stage;
}
public double getFailRate() {
return failRate;
}
public void setFailRate(double failRate) {
this.failRate = failRate;
}
}
소감
- Stream은 신이고 나는 병신이다.
- 처음에는 직접 Comparator을 구현했지만, thenComparing 이라는 편리한 함수가 있다는 것을 알고 이를 통해서 구현했다.
- 단 한줄로 해결이 되다니...^^