설명
오름차순으로 정렬이 된 두 배열이 주어지면 두 배열을 오름차순으로 합쳐 출력하는 프로그램을 작성하세요.
입력
첫 번째 줄에 첫 번째 배열의 크기 N(1<=N<=100)이 주어집니다.
두 번째 줄에 N개의 배열 원소가 오름차순으로 주어집니다.
세 번째 줄에 두 번째 배열의 크기 M(1<=M<=100)이 주어집니다.
네 번째 줄에 M개의 배열 원소가 오름차순으로 주어집니다.
각 리스트의 원소는 int형 변수의 크기를 넘지 않습니다.
출력
오름차순으로 정렬된 배열을 출력합니다.
예시 입력 1
3
1 3 5
5
2 3 6 7 9
예시 출력 1
1 2 3 3 5 6 7 9
소스 코드 1
import java.util.Scanner;
public class Main {//런타임 오류 남
public static int[] solution(int N, int M, int[] arr1, int[] arr2) {
int[] ans = new int[N + M];
int x = 0; //N배열 조작 변수
int y = 0; //M배열 조작 변수
for (int i = 0; i < N + M; i++) {
if (arr1[x] < arr2[y]) { //arr1 배열의 원소가 arr2 배열의 원소보다 작을 때
ans[i] = arr1[x++]; //ans배열에 넣어주고 x 카운트
if (x == N) { // arr1을 끝까지 읽었다는 뜻이므로 남은 arr2 원소 ans에 다 대입
for (int j = i+1; j < N + M; j++) {
ans[j] = arr2[y++];
}
break; //break 안 해주면 i for문이 계속 돈다.
}
} else {
ans[i] = arr2[y++]; //ans배열에 넣어주고 y 카운트
if (y == M) { // arr2을 끝까지 읽었다는 뜻이므로 남은 arr1 원소 ans에 다 대입
for (int j = i+1; j < N + M; j++) {
ans[j] = arr2[x++];
}
break;
}
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] arr1 = new int[N];
for (int i = 0; i < N; i++) {
arr1[i] = sc.nextInt();
}
int M = sc.nextInt();
int[] arr2 = new int[M];
for (int i = 0; i < M; i++) {
arr2[i] = sc.nextInt();
}
for (int s : solution(N, M, arr1, arr2)) {
System.out.print(s+" ");
}
}
}
소스 코드 2
import java.util.ArrayList;
import java.util.Scanner;
//두 배열 합치기 다른 풀이
public class Main {
public static ArrayList<Integer> solution(int N, int M, int[] arr1, int[] arr2) {
ArrayList<Integer> ans = new ArrayList<>();
int p1 = 0, p2 = 0;
while (p1 < N && p2 < M) { //p1이나 p2 둘중 하나가 배열을 끝까지 돌면 반복문 끝
if (arr1[p1] < arr2[p2]) {
ans.add(arr1[p1++]);
} else {
ans.add(arr2[p2++]);
}
}
while (p1 < N) {
ans.add(arr1[p1++]);
}
while (p2 < M) {
ans.add(arr2[p2++]);
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] arr1 = new int[N];
for (int i = 0; i < N; i++) {
arr1[i] = sc.nextInt();
}
int M = sc.nextInt();
int[] arr2 = new int[M];
for (int i = 0; i < M; i++) {
arr2[i] = sc.nextInt();
}
for (int s : solution(N, M, arr1, arr2)) {
System.out.print(s+" ");
}
}
}