PriorityQueue를 두 개 사용해 풀었다.
양수를 저장하는 positive PriorityQueue는 오름차순으로 정령하도록 선언하고
음수를 저장하는 negavite PriorityQueue는 내림차순으로 정렬하기 위해 Collections.reverseOrder()를 사용했다.
입력된 수의 조건에 따라 저장했다. 0이 입력됐을 때는 PriorityQueue의 peek()를 통해 절댓값을 비교해 출력했다.
변수 선언
Scanner scanner = new Scanner(System.in);
PriorityQueue<Integer> positive = new PriorityQueue<>();
PriorityQueue<Integer> negative = new PriorityQueue<>(Collections.reverseOrder());
int n = scanner.nextInt();
int num;
String result = "";
0이 입력되었을 때는 각각의 PriorityQueue가 비어있는지 확인 후 조건에 따라 결과에 더해줬다.
둘 다 비어있지 않으면 절댓값 비교를 통해 결과에 더해준다
if(num == 0)
{
if(positive.isEmpty() && negative.isEmpty())
{
result+="0\n";
}
else
{
if(positive.isEmpty())
{
result += negative.poll()+"\n";
}
else if(negative.isEmpty())
{
result += positive.poll()+"\n";
}
else
{
result += Math.abs(positive.peek()) >= Math.abs(negative.peek()) ? negative.poll()+"\n" : positive.poll()+"\n";
}
}
}
0이 아닌 수가 입력되었으면 조건에 따라 PriorityQueue에 더해준다.
else
{
if(num<0)
{
negative.add(num);
}
else
{
positive.add(num);
}
}
반복문으로 만들어 주면 끝.
결과 코드
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
PriorityQueue<Integer> positive = new PriorityQueue<>();
PriorityQueue<Integer> negative = new PriorityQueue<>(Collections.reverseOrder());
int n = scanner.nextInt();
int num;
String result = "";
for(int i = 0; i <n; i++)
{
num = scanner.nextInt();
if(num == 0)
{
if(positive.isEmpty() && negative.isEmpty())
{
result+="0\n";
}
else
{
if(positive.isEmpty())
{
result += negative.poll()+"\n";
}
else if(negative.isEmpty())
{
result += positive.poll()+"\n";
}
else
{
result += Math.abs(positive.peek()) >= Math.abs(negative.peek()) ? negative.poll()+"\n" : positive.poll()+"\n";
}
}
}
else
{
if(num<0)
{
negative.add(num);
}
else
{
positive.add(num);
}
}
}
System.out.println(result);
}
}
'백준' 카테고리의 다른 글
5430번:AC(Java) (1) | 2023.02.24 |
---|---|
1927번:최소 힙(Java) (0) | 2023.02.20 |
1302번: 베스트셀러(Java) (0) | 2023.02.19 |
1158번: 요세푸스 문제(Java) (2) | 2023.02.16 |
11399번: ATM(Java) (0) | 2023.02.12 |