-
[프로그래머스] 힙 - 이중순위큐알고리즘 공부 2020. 8. 14. 14:46
static int[] solution(String[] operations) { int[] answer = {0,0}; // 초기값 설정 // 최대값과 최소값을 처리하는 두개의 큐를 각각 만든다 PriorityQueue<Integer> maxQ=new PriorityQueue<Integer>(); PriorityQueue<Integer> minQ=new PriorityQueue<Integer>(); for(int i=0;i<operations.length;i++) { // 숫자 처리 코드 int endIndex=operations[i].length(); int num=0; if(operations[i].charAt(2)=='-') { //음수 처리 num=Integer.parseInt(operations[i].substring(3, endIndex)); num *=-1; } else{ //양수 처리 num=Integer.parseInt(operations[i].substring(2, endIndex)); } switch(operations[i].charAt(0)) { // insert 명령인경우 case 'I' : maxQ.add(num*-1); minQ.add(num); break; // delete 명령인경우 case 'D': // 삭제할 값이 없으면 break if(maxQ.size()==0)break; //최대값 삭제 if(operations[i].charAt(2)=='1') { int delete=maxQ.poll(); // 최대 힙에서 삭제후 maxQ.remove(delete*-1); // 최소 힙에서도 대응값 삭제 } else { int delete=minQ.poll(); // 최소 힙에서 삭제 후 minQ.remove(delete*-1); // 최대 힙에서도 대응값 삭제 } break; } } //최대값, 최소값 존재하면 출력 if(maxQ.size()>0) { answer[0]=maxQ.peek()*-1; answer[1]=minQ.peek(); } return answer; }
우선순위 큐를 이용하는 문제이다.
자바에서 제공하는 우선순위 큐 자료구조를 이용하고 싶어..
최대힙과 최소힙을 나누어서 처리하도록 하였다.
최대힙과 상반되는 최소힙은 숫자를 넣을 때 -1값을 곱하여 처리하였다.
'알고리즘 공부' 카테고리의 다른 글
[알고리즘 개념] 해시 알고리즘 (1) 2020.08.28