[C] 백준 11728 배열 합치기

z00m__in·2021년 5월 15일
0

Algorithm - Two Pointer

목록 보기
2/5

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

문제

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

제출 15755 정답 비율 44%





코드

#include <stdio.h>
#define MAX 1000

int main(void) {
	int N=0, M=0;

	scanf("%d %d", &N, &M);
	int* A = malloc(N * sizeof(int));
	int* B = malloc(M * sizeof(int));
	int* arr = malloc((N+M) * sizeof(int));

	for (int i = 0; i < N; i++) {
		scanf("%d", &A[i]);
	}
	for (int i = 0; i < M; i++) {
		scanf("%d", &B[i]);
	}

	int r = 0, s = 0;
	for (int i = 0; i < N + M; i++) {
		if (r == N) {
			arr[i] = B[s];
			s++;
		//A의 배열을 모두 읽은 경우 나머지는 다 B배열을 입력받게
		}else if (s == M) {
			arr[i] = A[r];
			r++;
		//B의 배열을 모두 읽은 경우 나머지는 다 A배열을 입력받게
		} else if (A[r] <= B[s]) {
			arr[i] = A[r];
			r++;
		//A가 B보다 작으면 A를 입력
		} else if (A[r] > B[s]) {
			arr[i] = B[s];
			s++;
		//B가 A보다 작으면 B를 입력
		}

	}

	for (int i = 0; i < N + M; i++) {
		printf("%d", arr[i]);
	}//출력
    

}
profile
우당탕탕 기록지

0개의 댓글

관련 채용 정보