Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and nrespectively.public class Solution { public void merge(int A[], int m, int B[], int n) { int k = m+n-1; int aIdx = m-1; int bIdx = n-1; while(aIdx >= 0 && bIdx >=0){ if(A[aIdx] >= B[bIdx]){ A[k] = A[aIdx]; aIdx--; }else{ A[k] = B[bIdx]; bIdx--; } k--; } // eg1: A={1,2,3}, B={4,5} B 先遍历完 跳出循环 因为长度正好是 m+n. 所以A不用再遍历了 // eg2: A={4,5}, B={1,2,3} A遍历完 B还没遍历完 跳入下面循环 while(bIdx >= 0){ A[k] = B[bIdx]; bIdx--; k--; } }}