88. Merge Sorted Array
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Notice
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 m and n respectively.
Example
A = [1, 2, 3, empty, empty]
, B = [4, 5]
After merge, A will be filled as [1, 2, 3, 4, 5]
分析:
这题的确很简单,用两个pointer分别指向两个array的最后一个数,然后根据它们的大小依次把它们添加到array A里(从末到头添加)
1 public class Solution { 2 public void merge(int[] A, int m, int[] B, int n) { 3 int pa = m - 1, pb = n - 1, p = m + n - 1; 4 5 while (pa >= 0 || pb >= 0) { 6 int a = pa >= 0 ? A[pa] : Integer.MIN_VALUE; 7 int b = pb >= 0 ? B[pb] : Integer.MIN_VALUE; 8 if (a >= b) { 9 A[p] = a; 10 pa--; 11 } else { 12 A[p] = b; 13 pb--; 14 } 15 p--; 16 } 17 } 18 }