프로그래머스 레벨 1 명예의 전당 문제를 풀이했다.
문제 내용이 간단해서 풀이에 3분 정도 소요한 것 같다. 단순한 문제일 수록 불필요한 로직을 잘 갈무리하는게 중요한 것 같다. 문제 풀이후에 다른 사람의 풀이를 보니 대부분 Java의 우선순위 큐 클래스를 활용하여 풀이한게 눈에 띄었다.
내 로직에는 매 반복마다 정렬해주는게 맘에 들지는 않았지만 k의 크기가 어차피 100이하라서 크게 지장을 줄 것 같지는 않아 리스트와 정렬 메소드를 사용했다!
HallOfFame1.java
package com.example.Programmers.Lv1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 프로그래머스 Lv1 - 명예의 전당
*/
public class HallOfFame1 {
public int[] solution(int k, int[] score) {
int[] answer = new int[score.length];
List<Integer> list = new ArrayList<>();
for (int i = 0; i < score.length; i++) {
list.add(score[i]);
Collections.sort(list);
if (list.size() > k) {
list.remove(0);
}
answer[i] = list.get(0);
}
return answer;
}
}
HallOfFame1Test.java
package com.example.Programmers.Lv1;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class HallOfFame1Test {
@Test
public void testHallOfFame1() {
HallOfFame1 h = new HallOfFame1();
int[] result1 = h.solution(3, new int[] { 10, 100, 20, 150, 1, 100, 200 });
int[] result2 = h.solution(4, new int[] { 0, 300, 40, 300, 20, 70, 150, 50, 500, 1000 });
int[] expected1 = new int[] { 10, 10, 10, 20, 20, 100, 100 };
int[] expected2 = new int[] { 0, 0, 0, 0, 20, 40, 70, 70, 150, 300 };
assertArrayEquals(expected1, result1);
assertArrayEquals(expected2, result2);
}
}