알고리즘
프로그래머스 level1 : 명예의 전당(1) - Java
mezo
2023. 6. 5. 21:45
728x90
반응형
1. ArrayList 사용 내림차순 정렬
기본이 오름차순 정렬이라서 내림차순 정렬하려면 Collections.reverseOrder() 써야함.
import java.util.*;
class Solution {
public int[] solution(int k, int[] score) {
int[] answer = new int[score.length];
List<Integer> sorting = new ArrayList<>();
for(int i = 0; i < score.length; i++){
sorting.add(score[i]);
Collections.sort(sorting, Collections.reverseOrder());
if(sorting.size() < k) answer[i] = sorting.get(sorting.size()-1);
else answer[i] = sorting.get(k-1);
}
return answer;
}
}
2. PriorityQueue 사용
기본이 오름차순 정렬이라서 젤 작은 값이 젤 앞에 오게됨
poll : 첫번째값 즉 제일 작은값 제거
peek : 첫번째값 가져오고 제거는 안함
import java.util.*;
class Solution {
public int[] solution(int k, int[] score) {
int[] answer = new int[score.length];
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i = 0; i < score.length; i++){
pq.add(score[i]);
if(pq.size() > k) pq.poll();
answer[i] = pq.peek();
}
return answer;
}
}
728x90
반응형