코딩테스트/[JAVA] 백준

[백준 | JAVA | 11286번] 절댓값 힙

냠냠쿠 2023. 12. 27. 10:29
728x90

 

https://www.acmicpc.net/problem/11286

 

📝 유튜브 풀이

https://www.youtube.com/watch?v=624DWEXSehw
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) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine());
		
		PriorityQueue<Integer> myQueue = new PriorityQueue<>((o1, o2)-> {

			int frist_abs = Math.abs(o1);
			int second_abs = Math.abs(o2);
			
			//절댓값이 같은 경우 음수 출력 
			if(frist_abs == second_abs) {
				return o1 > o2 ? 1 : -1;
			}
			
			// 절댓값 작은 데이터 출력
			return frist_abs - second_abs;
		});
		for( int i=0; i<N; i++) {
			int request = Integer.parseInt(br.readLine());
			
			if(request==0) {
				if(myQueue.isEmpty()) {
					System.out.println("0");
				} else {
					System.out.println(myQueue.poll());
				}
			} else {
				myQueue.add(request);
			}
		}
	}
}

 

📝 나의 풀이

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
 
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		//연산의 개수 
		int N = scanner.nextInt();
		
		//우선순위 큐 
		PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(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;
					
				}
			}
		});
		
		StringBuilder sb = new StringBuilder();
		
		for(int i=-0; i<N; i++) {
			int x = scanner.nextInt();
			if(x==0) {
				if(priorityQueue.isEmpty()) {
					sb.append("0").append("\n");
				} else {
					sb.append(priorityQueue.poll()).append("\n");
				}
			} else {
				priorityQueue.offer(x);
			}
		}
		System.out.println(sb);
	}
}
728x90