Post

[BaekJoon] #3273 - 두 수의 합 [Java][C++][Python]

[BaekJoon] #3273 - 두 수의 합 [Java][C++][Python]

문제 링크


1. 아이디어

합이 $x$인 쌍의 수를 구하는 문제이다. $n$이 최대 100,000이라 모든 쌍을 확인하는 $O(n^2)$은 느리므로, 수열을 오름차순으로 정렬하고 양 끝에 포인터를 두는 투 포인터를 쓴다. 두 포인터가 가리키는 수의 합이 $x$보다 작으면 왼쪽 수는 오른쪽 포인터 이하의 어떤 수와 짝을 지어도 합이 현재 합 이하라 $x$에 닿지 못하므로 왼쪽 포인터를 옮기고, 합이 $x$보다 크면 같은 이유로 오른쪽 포인터를 옮긴다. 두 포인터 바깥의 수는 이미 이런 비교에서 걸러졌거나 짝이 정해진 수라 다시 볼 필요가 없다. 합이 $x$이면 수가 서로 다르므로 두 수는 서로에게만 짝이 될 수 있어 쌍을 하나 세고 두 포인터를 함께 옮긴다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());

        int[] arr = new int[n];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(arr);

        int x = Integer.parseInt(br.readLine());

        int l = 0, r = n - 1;
        int cnt = 0;
        while (l < r) {
            if (arr[l] + arr[r] < x) {
                l++;
            } else if (arr[l] + arr[r] > x) {
                r--;
            } else {
                cnt++;
                l++;
                r--;
            }
        }

        System.out.println(cnt);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n;
    cin >> n;

    vector<int> v(n);
    for (int& x : v) cin >> x;
    sort(v.begin(), v.end());

    int x;
    cin >> x;

    int l = 0, r = n - 1;
    int cnt = 0;
    while (l < r) {
        if (v[l] + v[r] < x) {
            l++;
        } else if (v[l] + v[r] > x) {
            r--;
        } else {
            cnt++;
            l++;
            r--;
        }
    }

    cout << cnt;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import sys

input = sys.stdin.readline

input()
arr = sorted(map(int, input().split()))
x = int(input())

l, r = 0, len(arr) - 1
cnt = 0
while l < r:
    if arr[l] + arr[r] < x:
        l += 1
    elif arr[l] + arr[r] > x:
        r -= 1
    else:
        cnt += 1
        l += 1
        r -= 1

print(cnt)

This post is licensed under CC BY 4.0 by the author.