문제
programmers.co.kr/learn/courses/30/lessons/42628
코딩테스트 연습 - 이중우선순위큐
programmers.co.kr
코드
woovictory.github.io/2018/03/19/JavaCollectionPriorityQueue/
[Java] Priority Queue
이번에는 Priority Queue에 대해서 공부를 해보았습니다.
woovictory.github.io
자바의 PriorityQueue는 우선순위가 가장 작은 값을 출력하는 함수만 있기 때문에 이를 어떻게 다뤄서 최댓값을 출력할지 고민해보면 된다.
나는 마지막 원소를 제외한 모든 원소를 ArrayList에 담아놓고, 마지막 원소도 삭제한 뒤에 ArrayList 안의 값들을 다시 pq에 옮겨줬다.
import java.util.*;
class Solution {
public int[] solution(String[] operations) {
int[] answer = new int[2];
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(String op : operations){
if(op.equals("D 1")){
ArrayList<Integer> al = new ArrayList<>();
int size = pq.size();
for(int i=0; i<size; i++){
int num = pq.poll();
if(i<size-1){
al.add(num);
}
}
for(int i=0; i<al.size(); i++){
pq.add(al.get(i));
}
}else if(op.equals("D -1")){
pq.poll();
}else if(op.substring(0,1).equals("I")){
int num = Integer.parseInt(op.split("\\s")[1]);
pq.add(num);
}
}
int resultPqSize = pq.size();
for(int i=0; i<resultPqSize;i++){
if(i==0)
answer[1]=pq.poll();
else if(i==resultPqSize-1)
answer[0]=pq.poll();
else
pq.poll();
}
return answer;
}
}
'Preparing Coding Test > Programmers L3' 카테고리의 다른 글
[Java/프로그래머스/해시] Level 3: 베스트앨범 (0) | 2020.12.06 |
---|---|
[Java/프로그래머스/DFS] Level 3: 단어 변환 (0) | 2020.11.06 |
[Java/프로그래머스/DFS] 여행경로 (0) | 2020.11.05 |
[Java/프로그래머스/BFS] 네트워크 (0) | 2020.10.29 |
[Java/프로그래머스/힙(Heap)] 디스크 컨트롤러 (0) | 2020.10.20 |