투 포인터 - 좋은 수 구하기

김동헌·2023년 10월 31일

Algorithm

목록 보기
6/13
post-thumbnail

🔎 문제

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


🔍 문제 분석

(1) 자기 자신을 포함하면 안됨

(2) 투포인터를 사용하고, 배열은 오름차순 정렬을 사용한다.

(3) 투포인터 (1)과 (2)의 방식으로
start_index는 배열의 시작,
end_index는 배열의 끝에 위치하고 find 변수를 선언,
start_index + end_index = find일 때 (자기 자신 포함 x)
count++, break


투포인터 이동 원칙
A[i] + A[j] > K => j--;
A[i] + A[j] < K => i++;
A[i] + A[j] == K(K!=i, K!=j) => couint++; break;

i = start_index, j = end_index, K = find


👀 코드

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

public class BackJoon_1253 {

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(bf.readLine());
        int[] A = new int[N];
        StringTokenizer st = new StringTokenizer(bf.readLine());
        
        for (int i = 0; i < N; i++) {
            A[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(A);

        int count = 0;
        for (int i = 0; i < N; i++) {
            int find = A[i];
            int start_index = 0;
            int end_index = N-1;

            while (start_index < end_index) {
                if (A[start_index] + A[end_index] < A[i]) {
                    start_index++;
                }
                else if (A[start_index] + A[end_index] > A[i]) {
                    end_index--;
                }
                else if (A[start_index] + A[end_index] == find) {
                    // 자기 자신을 포함하면 안되므로 체크 한번
                    if (start_index != i && end_index != i) {
                        count++;
                        break;
                    }
                    else if (start_index == i) {
                        start_index++;
                    }
                    else if (end_index == i) {
                        end_index--;
                    }
                }
            }
        }
        System.out.println(count);
        bf.close();
    }
}
profile
백엔드 기록 공간😁

0개의 댓글