[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 };


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM