合並兩個排序的整數數組A和B變成一個新的數組。新數組也要有序。
樣例 1:
輸入: A=[1], B=[1]
輸出:[1,1]
樣例解釋:
返回合並后的數組。
樣例 2:
輸入: A=[1,2,3,4], B=[2,4,5,6]
輸出: [1,2,2,3,4,4,5,6]
樣例解釋:
返回合並后的數組。
思路:
先將兩個數組拼接起來,然后排序。(還有簡單的思路,這里暫時不實現)
實現代碼:
import java.util.Arrays; public class Solution { public static void main(String args[]) { int[] A = { 3, 2, 1, 4, 5 }; int[] B = { 5, 4 }; ArrayTwoInsert testArrayTwoInsert = new ArrayTwoInsert(); testArrayTwoInsert.mergeSortedArray(A, B); } } class Sort { /** * 數組排序算法實現 */ public void bubble(int[] array) { /** * 冒泡排序實現 */ int length = array.length; for (int i = 0; i < length; i++) { for (int j = 0; j < length - i - 1; j++) { if (array[j] > array[j + 1]) { int tmp = array[j]; array[j] = array[j + 1]; array[j + 1] = tmp; } } } System.out.println(Arrays.toString(array)); } public void select(int[] array) { /** * 選擇排序實現 */ int length = array.length; for (int i = 0; i < length; i++) { for (int j = i + 1; j < length; j++) { if (array[i] > array[j]) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } } System.out.println(Arrays.toString(array)); } } class ArrayTwoInsert { /** * 合並兩個排序的整數數組A和B變成一個新的數組。新數組也要有序。(輸入的兩個數組已排序) */ public int[] mergeSortedArray(int[] A, int[] B) { int[] Twoarray = new int[A.length + B.length]; for (int i = 0; i < A.length; i++) { Twoarray[i] = A[i]; } for (int j = 0; j < B.length; j++) { Twoarray[A.length + j] = B[j]; } Sort testSort = new Sort(); testSort.select(Twoarray); System.out.println(Arrays.toString(Twoarray)); return Twoarray; } }