LeetCode | Merge Sorted Array(歸併有序陣列)
阿新 • • 發佈:2019-01-21
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 (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 andn respectively.
題目解析:
將A和B兩個數組合併到A中,A中有足夠的空間。我們可以利用從後向前比較,來移動,就不需要額外申請空間了。這道題目跟《 面試題4替換空格》相似,都是從後向前去遍歷。
class Solution { public: void merge(int A[], int m, int B[], int n) { int i = m-1; int j = n-1; int k = m+n-1; while(i>=0 && j>=0){ if(A[i] > B[j]){ A[k--] = A[i--]; }else{ A[k--] = B[j--]; } } while(j>=0){ A[k--] = B[j--]; } } };