코딩테스트 연습 > 코딩테스트 입문 > 진료순서 정하기
외과의사 머쓱이는 응급실에 온 환자의 응급도를 기준으로 진료 순서를 정하려고 합니다. 정수 배열 emergency가 매개변수로 주어질 때 응급도가 높은 순서대로 진료 순서를 정한 배열을 return하도록 solution 함수를 완성해주세요.
| emergency | result |
|---|---|
| [3, 76, 24] | [3, 1, 2] |
| [1, 2, 3, 4, 5, 6, 7] | [7, 6, 5, 4, 3, 2, 1] |
| [30, 10, 23, 6, 100] | [2, 4, 3, 5, 1] |
나의 문제 풀이
class Solution {
public int[] solution(int[] emergency) {
int[] emergencyCopy = emergency.clone();
HashMap<Integer, Integer> sorting = new HashMap<>();
// for (int i = 0; i < emergency.length; i++) {
// for (int j = i + 1; j < emergency.length; j++) {
// if (emergency[i] < emergency[j]) {
// int temp = emergency[i];
// emergency[i] = emergency[j];
// emergency[j] = temp;
// }
// }
// }
// ----- for문 대신 Arrays.stream 사용하기 -----
Integer[] list = Arrays.stream(emergency).boxed().toArray(Integer[]::new);
Arrays.sort(list, Collections.reverseOrder());
emergency = Arrays.stream(list).mapToInt(Integer::valueOf).toArray();
int v = 1;
for(int e: emergency){
sorting.put(e,v);
v++;
}
int[] answer = new int[emergency.length];
for (int i=0; i<answer.length; i++){
answer[i] = sorting.get(emergencyCopy[i]);
}
return answer;
}
}
다른 사람의 문제 풀이
class Solution {
public static int[] solution(int[] emergency) {
int[] answer = new int[emergency.length];
for (int i = 0; i < emergency.length; i++) {
if (answer[i] != 0) {
continue;
}
int idx = 1;
for (int j = 0; j < emergency.length; j++) {
if (emergency[i] < emergency[j]) {
idx++;
}
}
answer[i] = idx;
}
return answer;
}
}
나의 코드
반복문을 사용해 emergency 배열을 역순으로 정렬하고 HashMap의 key로 넣었다. HashMap의 value는 순서대로 1, 2, 3, ...을 넣어주었다.
초기에 emergency 배열을 clone 해놓고, 이 배열의 순서대로 HashMap에서 key를 찾아서 value를 answer 배열에 반환하였다.
📌 배열 역순 정렬을
Collections.reverseOrder()를 사용하여 좀 더 간단하게 정리하였다.
다른 사람의 코드
answer 배열을 0으로 초기화 해두고,
반복문을 사용하여 배열의 다른 인덱스 값보다 작을 경우 idx값에 1씩 더해주면서 순서를 만든다.
오랜만에 코테 연습을 했더니 머리가 굳어버린 기분 ~,,
오늘부터 다시 열심히 해야징..