Post

[백준] 20922번 - 겹치는 건 싫어 [Java][C++]

[백준] 20922번 - 겹치는 건 싫어 [Java][C++]

문제 링크


1. 문제 풀이

주어진 수열에서 같은 정수를 $K$ 개 이하로 포함하는 가장 긴 구간의 길이를 구하는 문제로 투 포인터를 활용하면 해결할 수 있다. 카운팅 배열을 통해 구간 내 각 수의 개수를 세며 오른쪽 포인터를 이동할 때 $K$ 개 미만으로 포함하고 있으면 이동하며 최대 길이를 갱신하고, $K$ 개 이상 포함하고 있으면 왼쪽 포인터를 이동시키는 과정을 반복했다.


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
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 = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        int K = Integer.parseInt(st.nextToken());

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

        int left = 0;
        int right = 0;
        int max = 0;  // 최대 길이
        int[] cntArr = new int[1 + 100_000];  // 카운팅 배열

        while (right < N) {
            if (cntArr[arr[right]] < K) {
                cntArr[arr[right]]++;
                right++;
                max = Math.max(max, right - left);
            } else {
                cntArr[arr[left]]--;
                left++;
            }
        }

        System.out.println(max);
    }
}

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

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

    int n, k;
    cin >> n >> k;

    vector<int> v(n);
    for (int& x : v) cin >> x;

    int l = 0;
    int r = 0;
    int mx = 0;                      // 최대 길이
    vector<int> cntArr(1 + 100000);  // 카운팅 배열

    while (r < n) {
        if (cntArr[v[r]] < k) {
            cntArr[v[r]]++;
            r++;
            mx = max(mx, r - l);
        } else {
            cntArr[v[l]]--;
            l++;
        }
    }

    cout << mx;
}

3. 풀이 정보

1. 투 포인터 [Java]

언어시간메모리코드 길이
Java 11316 ms32912 KB1040 B

2. 투 포인터 [C++]

언어시간메모리코드 길이
C++ 1720 ms3196 KB573 B

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