문제
정렬되어있는 두 배열 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
예제 입력 2 복사
2 1
4 7
1
예제 출력 2 복사
1 4 7
예제 입력 3 복사
4 3
2 3 5 9
1 4 7
예제 출력 3 복사
1 2 3 4 5 7 9
내 답안
1. 투 포인터 활용
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());
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
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 start_index=0, end_index=0;
int index=0;
while(start_index!=N && end_index!=M){
if(A[start_index]<=B[end_index]){
sb.append(A[start_index++]+" ");
} else {
sb.append(B[end_index++]+" ");
}
}
if(start_index!=N){
for(int i=start_index;i<N;i++){
sb.append(A[i]+" ");
}
}
if(end_index!=M){
for(int i=end_index;i<M;i++){
sb.append(B[i]+" ");
}
}
System.out.println(sb);
}
}
2. 이 문제의 경우 전체 배열 값을 정렬하는 것이므로
Arrays.sort를 사용해서 정렬하는 방법도 있다.
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());
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[] A = new int[N];
int[] B = new int[M];
int[] C = new int[N+M];
int index=0;
st = new StringTokenizer(br.readLine());
for(int i=0;i<N;i++){
A[i] = Integer.parseInt(st.nextToken());
C[index++] = A[i];
}
st = new StringTokenizer(br.readLine());
for(int i=0;i<M;i++){
B[i] = Integer.parseInt(st.nextToken());
C[index++] = B[i];
}
Arrays.sort(C);
for(int i=0;i<N+M;i++)
sb.append(C[i]+" ");
System.out.println(sb);
}
}
'스터디 > Algorithm' 카테고리의 다른 글
[백준] 불 4179 java - bfs (0) | 2024.05.03 |
---|---|
[프로그래머스스쿨] 가장 큰 수 java (lv.2) (0) | 2024.05.03 |
[백준] 겹치는 건 싫어 java - two pointer (1) | 2024.05.02 |
[백준] 폴리오미노 java - greedy (0) | 2024.04.17 |
[프로그래머스] 완주하지 못한 선수 java (lv. 1) (0) | 2024.04.11 |