100세까지 코딩
[do it 알고리즘] 백준 11286 (우선순위 큐) 본문
문제 설명
풀기 전 생각
- 반복 규칙은 간단하니 우선순위 큐의 정렬 기준을 만드는게 핵심
- 절대값을 추출하여 절대값이 작은 것을 우선
- 절대값이 같으면 음수를 우선
- 큐를 정의한 후, 입력이 = 0일때 pq가 비어있으면 '0'출력 아니면 큐에서 한개 출력
- 입력이 0이 아니면 큐에 삽입
import java.util.PriorityQueue;
import java.util.Scanner;
public class Baek11286{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
StringBuilder sb = new StringBuilder();
PriorityQueue<Integer> pq = new PriorityQueue<Integer>((o1,o2)->{
int firstNum = Math.abs(o1);
int secondNum = Math.abs(o2);
if(firstNum==secondNum){
return o1 > o2 ? 1 : -1;
}
return firstNum-secondNum;
});
for(int i = 0; i < N; i++){
int num = sc.nextInt();
if(num==0){
if(pq.isEmpty()){
sb.append("0\n");
}else{
sb.append(pq.remove()+"\n");
}
}else{
pq.add(num);
}
}
System.out.println(sb.toString());
}
}
리뷰
체감상 실버 1만큼 어렵지는 않았다.
comparable, comparator 처럼 람다식으로 정렬을 작성할 줄 알면 쉬웠던 문제
절댓값 구하는 함수도 알면 좋다
'코딩테스트 > 자바' 카테고리의 다른 글
[do it 알고리즘] 백준 1427 (선택 정렬) (1) | 2023.10.05 |
---|---|
[do it 알고리즘] 백준 2750 (버블 정렬) (0) | 2023.10.05 |
[do it 알고리즘] 백준 2164 (큐) (0) | 2023.09.29 |
[do it 알고리즘] 백준 1874 (스택) (0) | 2023.09.28 |
[do it 알고리즘] 백준 12891 (슬라이딩 윈도우) (1) | 2023.09.25 |