Algorithm/COS PRO 1급 기출문제
[COS PRO 1급 기출문제 - Java] 1-7 병합 and 정렬
goakgoak
2020. 12. 21. 13:08
문제 유형
빈 칸 채우기
문제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.util.*; class Main{ public int[] solution(int[] arrA, int[] arrB) { int arrA_idx = 0, arrB_idx = 0; int arrA_len = arrA.length; int arrB_len = arrB.length; int answer[] = new int[arrA_len + arrB_len]; int answer_idx = 0; while(________){ if(arrA[arrA_idx] < arrB[arrB_idx]) answer[answer_idx++] = arrA[arrA_idx++]; else answer[answer_idx++] = arrB[arrB_idx++]; } while(________) answer[answer_idx++] = arrA[arrA_idx++]; while(________) answer[answer_idx++] = arrB[arrB_idx++]; return answer; } public static void main(String[] args) { Main sol = new Main(); int[] arrA = {-2, 3, 5, 9}; int[] arrB = {0, 1, 5}; int[] ret = sol.solution(arrA, arrB); System.out.println("solution 함수의 반환 값은 " + Arrays.toString(ret) + " 입니다."); } } | cs |
풀이
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.util.*; class Main{ public int[] solution(int[] arrA, int[] arrB) { int arrA_idx = 0, arrB_idx = 0; int arrA_len = arrA.length; int arrB_len = arrB.length; int answer[] = new int[arrA_len + arrB_len]; int answer_idx = 0; while(arrA_idx < arrA_len && arrB_idx < arrB_len){ if(arrA[arrA_idx] < arrB[arrB_idx]) answer[answer_idx++] = arrA[arrA_idx++]; else answer[answer_idx++] = arrB[arrB_idx++]; } while(arrA_idx < arrA_len) answer[answer_idx++] = arrA[arrA_idx++]; while(arrB_idx < arrB_len) answer[answer_idx++] = arrB[arrB_idx++]; return answer; } public static void main(String[] args) { Main sol = new Main(); int[] arrA = {-2, 3, 5, 9}; int[] arrB = {0, 1, 5}; int[] ret = sol.solution(arrA, arrB); System.out.println("solution 함수의 반환 값은 " + Arrays.toString(ret) + " 입니다."); } } | cs |