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 n respectively.spa
給定兩個有序數組A和B,將B中的元素插入A(假設A有足夠大的空間),保持有序性指針
Tip: A和B的大小已知,即合併完成後的數組大小肯定。code
將指針指向A和B的尾端,從數組的尾端(最大值)處開始合併。若B中仍有剩餘元素,所有插入A的頭部。blog
代碼ip
1 class Solution { 2 public: 3 void merge(int A[], int m, int B[], int n) { 4 // Note: The Solution object is instantiated only once and is reused by each test case. 5 if(B==NULL || n==0) 6 return; 7 8 int p=m-1, q=n-1, cur=m+n-1; 9 while(p>=0 && q>=0) 10 { 11 if(A[p]>=B[q]) 12 { 13 A[cur--] = A[p--]; 14 } 15 else 16 { 17 A[cur--] = B[q--]; 18 } 19 } 20 while(q>=0) 21 A[cur--] = B[q--]; 22 } 23 };