728x90
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
이중우선순위큐라고 해서 우선순위큐를 2개 사용해서 문제를 해결했다.
pq_asc는 오름차순 pq , pq_desc는 내림차순 pq이다.
내림차순의 경우 Collections.reversOrder()를 사용하면 쉽게 정렬시킬 수 있다는 걸 알았다.!
stack이나 list에서만 remove가 가능한 것이 아니라 queue에서도 remove가 가능하다는 사실을 잊지말 것.
전체코드
import java.io.*;
import java.util.*;
class Solution {
public int[] solution(String[] operations) {
PriorityQueue<Integer> pq_asc = new PriorityQueue<>();
PriorityQueue<Integer> pq_desc = new PriorityQueue<>(Collections.reverseOrder());
int cnt = 0;
for(int i=0; i<operations.length; i++){
String[] arr = operations[i].split(" ");
if(arr[0].equals("I")){
pq_asc.offer(Integer.valueOf(arr[1]));
pq_desc.offer(Integer.valueOf(arr[1]));
cnt++;
}else{
if(arr[1].equals("1")){
if(cnt > 0){
int tmp = pq_desc.poll();
pq_asc.remove(tmp);
cnt--;
}else{
continue;
}
}else{
if(cnt > 0){
int tmp = pq_asc.poll();
pq_desc.remove(tmp);
cnt--;
}else{
continue;
}
}
}
}
int[] answer = new int[2];
if(pq_desc.size() == 0){
answer[0] = 0;
if(pq_asc.size() == 0){
answer[1] = 0;
}else{
answer[1] = pq_asc.poll();
answer[0] = answer[1];
}
}else{
answer[0] = pq_desc.poll();
if(pq_asc.size() == 0){
answer[1] = answer[0];
}else{
answer[1] = pq_asc.poll();
}
}
return answer;
}
}
728x90
'코테 > Algorithm' 카테고리의 다른 글
[Programmers] 등굣길 (JAVA) (0) | 2024.07.30 |
---|---|
[Programmers] 단어 변환 (JAVA) (0) | 2024.07.29 |
[Programmers] 귤 고르기 (JAVA) (0) | 2024.07.25 |
[Programmers] 연속된 부분 수열의 합 (JAVA) (2) | 2024.07.23 |
[Programmers] 튜플 (JAVA) (1) | 2024.07.22 |