Post

[백준] 3273번 - 두 수의 합 [Java][C++]

[백준] 3273번 - 두 수의 합 [Java][C++]

문제 링크


1. 문제 풀이

주어진 수열에서 두 수의 합이 $x$ 인 쌍의 개수를 구하는 문제다. 주어진 수열을 정렬한 후 양 끝에 포인터를 두는 투 포인터를 활용하면 해결할 수 있다. 포인터가 가리키는 두 수의 합이 $x$ 보다 작으면 왼쪽 포인터를 이동시켜 두 수의 합이 커지게 하면 되고, 두 수의 합이 $x$ 보다 크면 오른쪽 포인터를 이동시켜 두 수의 합이 작아지게 하면 된다. 두 수의 합이 $x$ 일 경우 개수를 세며 두 포인터를 모두 이동시켜도 된다.(겹치는 수가 없으므로)


2. 코드

1. 투 포인터 [Java]

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
36
37
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));
        StringTokenizer st;

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

        int[] arr = new int[n];
        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 left = 0;
        int right = n - 1;
        int cnt = 0;
        while (left < right) {
            if (arr[left] + arr[right] < x) {
                left++;
            } else if (arr[left] + arr[right] > x) {
                right--;
            } else {
                cnt++;
                left++;
                right--;
            }
        }

        System.out.println(cnt);
    }
}

2. 투 포인터 [C++]

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
#include <bits/stdc++.h>
using namespace std;

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

    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;
    int 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;
}

3. 풀이 정보

1. 투 포인터 [Java]

언어시간메모리코드 길이
Java 11304 ms25568 KB953 B

2. 투 포인터 [C++]

언어시간메모리코드 길이
C++ 1712 ms2412 KB532 B

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