✔ 내 답 -> 정답
https://hianna.tistory.com/601
JAVA 배열 합치는 방법
import java.util.*;
import java.lang.*;
public class P3_1 {
public static int[] solution(int[] arr1, int[] arr2) {
int[] arr = new int[arr1.length+arr2.length];
System.arraycopy(arr1,0,arr,0,arr1.length);
System.arraycopy(arr2,0,arr,arr1.length,arr2.length);
Arrays.sort(arr);
return arr;
}
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
int a1 = kb.nextInt();
int[] arr1= new int[a1];
for(int i=0;i<a1;i++) arr1[i] = kb.nextInt();
int a2= kb.nextInt();
int[] arr2= new int[a2];
for(int j=0;j<a2;j++) arr2[j] = kb.nextInt();
for( int x: solution(arr1,arr2)) System.out.print(x+" ");
}
}
위는 매우 비효율적이다.
강의 처럼 O(n)방법을 사용한다.
✔️ 강의 답
import java.util.*;
public class Main{
public static ArrayList<Integer> solution(int[] arr1 , int[] arr2){
ArrayList<Integer> answer = new ArrayList<>();
int op =0, tp=0;
while(op<arr1.length && tp<arr2.length) {
if(arr1[op]<=arr2[tp]) {
answer.add(arr1[op]);
op++;
}
else {
answer.add(arr2[tp]);
tp++;
}
}
while(op<arr1.length) answer.add(arr1[op++]);
while(tp<arr2.length) answer.add(arr2[tp++]);
return answer;
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int a1_len = kb.nextInt();
int[] arr1 = new int[a1_len];
for(int i=0; i<a1_len;i++) {
arr1[i]=kb.nextInt();
}
int a2_len = kb.nextInt();
int[] arr2 = new int[a2_len];
for(int i=0; i<a2_len;i++) {
arr2[i]=kb.nextInt();
}
for(int x : solution(arr1,arr2)) System.out.print(x+" ");
}
}