개발 μ₯¬μŠ€

[λ°±μ€€/Java] 2470 두 μš©μ•‘ λ³Έλ¬Έ

μΉ΄ν…Œκ³ λ¦¬ μ—†μŒ

[λ°±μ€€/Java] 2470 두 μš©μ•‘

DevJuice 2024. 8. 20. 09:43
λ°˜μ‘ν˜•

πŸ”— 문제 링크: https://www.acmicpc.net/problem/2470

πŸ” ν•΄κ²° κ³Όμ •

μ„œλ‘œ ν•©ν–ˆμ„ λ•Œ κ·Έ μ ˆλŒ“κ°’μ΄ 0에 제일 κ°€κΉŒμš΄ 두 μš©μ•‘μ„ μ°Ύμ•„λ‚΄λŠ” 것이 문제의 ν•΅μ‹¬μ΄λ―€λ‘œ 투 포인터 방식을 ν™œμš©(μ‹œκ°„ λ³΅μž‘λ„: O(N), N: μš©μ•‘μ˜ 개수)ν•˜μ˜€μŠ΅λ‹ˆλ‹€.

두 μš©μ•‘μ˜ μ ˆλŒ“κ°’μ— λŒ€ν•œ μ²˜λ¦¬μ™€ 두 μš©μ•‘μ„ μ„œλ‘œ μ €μž₯ν•˜λŠ” 과정에 μžˆμ–΄μ„œ 고민을 μ’€ ν–ˆμ—ˆλ˜ λ¬Έμ œμž…λ‹ˆλ‹€.


✏️ μ½”λ“œ

import java.io.*;
import java.util.Arrays;

public class Main {

    private static final String SPACE = " ";

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(br.readLine());
        int[] liquids = Arrays.stream(br.readLine().split(SPACE))
                .mapToInt(Integer::parseInt)
                .toArray();

        Arrays.sort(liquids);

        int[] result = getResult(liquids, n);

        bw.write(result[0] + SPACE + result[1]);
        bw.flush();
        bw.close();
    }

    private static int[] getResult(int[] liquids, int n) {
        int leftIdx = 0;
        int rightIdx = n - 1;
        int resultLeft = -1;
        int resultRight = -1;
        int tempSum = Integer.MAX_VALUE;

        while (leftIdx < rightIdx) {
            int curSum = liquids[leftIdx] + liquids[rightIdx];

            if (Math.abs(curSum) < Math.abs(tempSum)) {
                tempSum = curSum;
                resultLeft = liquids[leftIdx];
                resultRight = liquids[rightIdx];
            }

            if (curSum < 0) {
                ++leftIdx;
            } else {
                --rightIdx;
            }
        }

        return new int[]{resultLeft, resultRight};
    }
}
λ°˜μ‘ν˜•