1253번: 좋다

Joo·2022년 11월 21일

백준

목록 보기
73/113

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

문제

N개의 수 중에서 어떤 수다른 수 두 개의 합으로 나타낼 수 있다면 그 수를 “좋다(GOOD)”고 한다.

N개의 수가 주어지면 그 중에서 좋은 수의 개수는 몇 개인지 출력하라.

수의 위치가 다르면 값이 같아도 다른 수이다.

입력

첫째 줄에는 수의 개수 N(1 ≤ N ≤ 2,000), 두 번째 줄에는 i번째 수를 나타내는 Ai가 N개 주어진다. (|Ai| ≤ 1,000,000,000, Ai는 정수)

출력

좋은 수의 개수를 첫 번째 줄에 출력한다.

예제 입력 1

10
1 2 3 4 5 6 7 8 9 10

예제 출력 1

8

코드

  • isGoodNumber의 매개변수로 sequence[index]를 넘기는 실수를 함
    • 이렇게 하면 isGoodNumber에서 같은 값이면서 위치가 다른 경우를 구별하지 못함
package two_pointer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main_1253 {

    private static int lengthOfSequence;
    private static int result;
    private static int[] sequence;

    public static void main(String[] args) throws IOException {
        input();
        process();
        output();
    }

    private static void input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        lengthOfSequence = Integer.parseInt(br.readLine());

        sequence = new int[lengthOfSequence];

        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < lengthOfSequence; i++) {
            sequence[i] = Integer.parseInt(st.nextToken());
        }
    }

    private static void process() {
        Arrays.sort(sequence);

        for (int index = 0; index < lengthOfSequence; index++) {
            if (isGoodNumber(index)) {
                result++;
            }
        }
    }

    private static boolean isGoodNumber(int index) {
        int target = sequence[index];
        int left = 0;
        int right = lengthOfSequence - 1;
        int sum;

        while (left < right) {
            if (left == index) {
                left++;
                continue;
            }

            if (right == index) {
                right--;
                continue;
            }

            sum = sequence[left] + sequence[right];

            if (sum < target) {
                left++;
            }

            if (sum > target) {
                right--;
            }

            if (sum == target) {
                return true;
            }
        }

        return false;
    }

    private static void output() {
        System.out.println(result);
    }

}

0개의 댓글