https://leetcode.com/problems/merge-sorted-array/數組
Given two sorted integer arrays A and B, merge B into A as one sorted array.markdown
Note:spa
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are mand n respectively.code
題意:把兩個有序數組合併成一個有序數組element
思路:逐個比較,小的複製給臨時數組,最後把臨時數組複製給Aleetcode
實現:get
public class Solution { public void merge(int A [], int m, int B[], int n) { int [] C = new int[ m + n]; for (int i = 0, j = 0, k = 0; k < m + n ; k ++) { if (i == m ) {// A數組用完,把B所有複製到C C[ k] = B[ j++]; continue ; } if (j == n ) {// B數組用完,把A所有複製到C C[ k] = A[ i++]; continue ; } if (A [i ] > B [j ])// 小的複製給C C[ k] = B[ j++]; else C[ k] = A[ i++]; } System. arraycopy( C, 0, A, 0, m + n); // 把C複製給A } }