[LeetCode] Merge Sorted Array
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.
考虑从后往前比较,这样就不会产生需要数据后移的问题了。时间复杂度O(n+m)
1 class Solution { 2 public: 3 void merge(int A[], int m, int B[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int index = m + n - 1; 7 int aIndex = m - 1; 8 int bIndex = n - 1; 9 while(0 <= aIndex && 0 <= bIndex) 10 { 11 if (B[bIndex] > A[aIndex]) 12 { 13 A[index--] = B[bIndex--]; 14 } 15 else 16 { 17 A[index--] = A[aIndex--]; 18 } 19 } 20 21 while(0 <= aIndex) 22 { 23 A[index--] = A[aIndex--]; 24 } 25 26 while(0 <= bIndex) 27 { 28 A[index--] = B[bIndex--]; 29 } 30 } 31 };