Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 백준_구간합구하기
- 백준11003
- 백준2023
- 정렬알고리즘
- 백준11724
- 백준1517
- 백준1874
- Java
- 자바
- 백준13023
- 백준1427
- 구간합
- 백준12891
- 백준2018
- 백준1260
- 백준1546
- 버블소트
- 백준_11659
- 백준2750
- 백준1377
- stack
- 백준1940
- 백준17298
- 백준11720
- 백준11286
- 백준11399
- 백준1253
- 백준2751
- 백준10998
- 백준
Archives
- Today
- Total
HOONDOC
[백준]11286 절댓값힙 - 자바/Java 본문
11286번: 절댓값 힙
🌱풀이
우선순위 큐를 사용해겠다는 생각은 했는데, 커스터마이징을 어떻게 해야 하는지 몰랐다. 우선순위의 기준을 입력하는 방식을 배웠던 문제였다.
💡 메모리 : 29428KB, 시간 832ms
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
PriorityQueue<Integer> pq = new PriorityQueue<>((o1,o2) -> {
int first_abs = Math.abs(o1);
int second_abs = Math.abs(o2);
if(first_abs == second_abs)
return o1 > o2 ? 1 : -1;
else
return first_abs - second_abs;
});
for(int i = 0; i<N; i++) {
int request = Integer.parseInt(br.readLine());
if(request == 0) {
if(pq.isEmpty()) System.out.println("0");
else System.out.println(pq.poll());
}
else pq.add(request);
}
}
}
🪴코드 리뷰
🌿
이전에 작성했던 코드다. 우선순위 큐의 정렬 기준을 커스터마이징 한 건 똑같은데, 그 방식이 좀 다르다.
💡 풀이자 : 본인, 메모리 : 97032KB, 시간 856ms
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int N = sc.nextInt();
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(Math.abs(o1) > Math.abs(o2)) return Math.abs(o1) - Math.abs(o2);
else if( Math.abs(o1) == Math.abs(o2)) return o1-o2;
else return -1;
}});
for(int i = 0; i<N; i++) {
int a = sc.nextInt();
if(a == 0) {
if(pq.isEmpty()) sb.append("0\\n");
else sb.append(pq.poll()+"\\n");
}
else
pq.add(a);
}
System.out.print(sb.toString());
sc.close();
}
}
Conclusion
다른 사람들의 코드들도 다 나처럼 작성되어있다. 시간, 메모리의 차이는 BufferedWriter를 썼다는 정도. Comparator나 o1,o2 변수를 추가하여 기준을 커스터마이징 하는 방법론은 따로 시간을 내서 정리해야겠다.
'문제 풀이 > BAEKJOON' 카테고리의 다른 글
[백준]1377 버블 소트 - 자바/Java (0) | 2023.01.02 |
---|---|
[백준]2750 수 정렬하기 1 - 자바/Java (0) | 2022.12.31 |
[백준]1253 좋다 - 자바/Java (0) | 2022.12.31 |
[백준]17298 오큰수 - 자바/Java (1) | 2022.12.30 |
[백준]1874 스택 수열 - 자바/Java (0) | 2022.12.30 |