1 minute read

πŸ“Œ λ‚œμ΄λ„

πŸ₯‡ Gold 5


πŸ“Œ 문제

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


image


πŸ“Œ 풀이

일단 이 문제λ₯Ό 보고 λ“  생각은 정렬을 ν•˜κΈ°λŠ” ν•΄μ•Όν•˜λŠ”λ°, Arrays.Sortλ₯Ό μ‚¬μš©ν•˜λ©΄ o(n^2) = 10,000,000,000 의 μ‹œκ°„λ³΅μž‘λ„κ°€ 생긴닀.
λ”°λΌμ„œ, o(nlog(n))의 μ‹œκ°„λ³΅μž‘λ„μΈ μš°μ„ μˆœμœ„ 큐λ₯Ό ν†΅ν•΄μ„œ 정렬을 ν•˜μ˜€λ‹€.

ν•˜μ§€λ§Œ μš°μ„ μˆœμœ„ 큐λ₯Ό μ‚¬μš©ν•˜λ©΄ κ°€μž₯ 큰 값은 μ•Œ 수 μžˆμ§€λ§Œ, κ°€μž₯ μž‘μ€ 값은 μ•Œ μˆ˜κ°€ μ—†λ‹€.
κ·Έλž˜μ„œ μ˜€λ¦„μ°¨μˆœ μš°μ„ μˆœμœ„ 큐와, λ‚΄λ¦Όμ°¨μˆœ μš°μ„ μˆœμœ„ 큐 λ‘κ°œλ₯Ό λ§Œλ“€μ–΄μ„œ, μ„œλ‘œ 값이 같을 λ•ŒκΉŒμ§€ 비ꡐλ₯Ό ν•΄μ£Όμ—ˆλ‹€.
λ‹€μŒμ€ κ·Έ μ½”λ“œμ΄λ‹€.


πŸ“Œ Code

package BOJ.TwoPointer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class N2470 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        int N = Integer.parseInt(br.readLine());

        PriorityQueue<Integer> ascend = new PriorityQueue<>();
        PriorityQueue<Integer> descend = new PriorityQueue<>(Collections.reverseOrder());
        st = new StringTokenizer(br.readLine());
        int num;

        for (int i = 0; i < N; i++) {
            num = Integer.parseInt(st.nextToken());
            ascend.add(num);
            descend.add(num);
        }

        int max = descend.remove();
        int min = ascend.remove();
        int[] closeZero = {max, min};

        while (max != min) {
            if (max + min > 0) {
                max = descend.remove();
            } else {
                min = ascend.remove();
            }
            if (max == min) {
                break;
            }
            if (Math.abs(closeZero[0] + closeZero[1]) > Math.abs(max + min)) {
                closeZero = new int[]{max, min};
            }
        }
        System.out.println(closeZero[1] + " " + closeZero[0]);
    }
}

package (이름); λ₯Ό λ•Œκ³ , class 이름을 Main으둜 λ³€κ²½ν•˜λ©΄ λœλ‹€.



개인 곡뢀 기둝용 λΈ”λ‘œκ·Έμž…λ‹ˆλ‹€.
ν‹€λ¦¬κ±°λ‚˜ 였λ₯˜κ°€ μžˆμ„ 경우 μ œλ³΄ν•΄μ£Όμ‹œλ©΄ κ°μ‚¬ν•˜κ² μŠ΅λ‹ˆλ‹€.😁