코딩테스트/백준

[백준 11728] 배열 합치기 (Java) - 투포인터

imachill7guy 2025. 4. 16. 18:18

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

배열 합치기

문제

정렬되어있는 두 배열 A와 B가 주어진다. 두 배열을 합친 다음 정렬해서 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 배열 A의 크기 N, 배열 B의 크기 M이 주어진다. (1 ≤ N, M ≤ 1,000,000)

둘째 줄에는 배열 A의 내용이, 셋째 줄에는 배열 B의 내용이 주어진다. 배열에 들어있는 수는 절댓값이 109보다 작거나 같은 정수이다.

출력

첫째 줄에 두 배열을 합친 후 정렬한 결과를 출력한다.

예제 입력 1 복사

2 2
3 5
2 9

예제 출력 1 복사

2 3 5 9

풀이

import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

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()); // A 배열크기
        int M = Integer.parseInt(st.nextToken()); // B 배열크기

        int[] A = new int[N];
        int[] B = new int[M];

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

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

        int i = 0;
        int j = 0;
        int k = 0;
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        while (i<N && j<M){
            if (A[i] <= B[j]){
                bw.write(A[i++] + " ");
            }else{
                bw.write(B[j++] + " ");
            }
        }

        while (i < N) bw.write(A[i++] + " ");
        while (j < M) bw.write(B[j++] + " ");
        
        bw.flush();
        bw.close();
    }
}