CoderJesse  
wangjiexi@CS.PKU

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.

归并排序。

 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 tag1 = m-1,tag2 = n-1;
 7         for(int i =  m+n-1;i >= 0 ; i--)
 8         {
 9             if(tag1 == -1 || tag2 == -1)
10             {
11                 if(tag1 == -1)
12                 {
13                     A[i] = B[tag2];
14                     tag2--;                   
15                 }
16                 else
17                 {
18                     A[i] = A[tag1];
19                     tag1--;                    
20                 }
21             }
22             else
23             {
24                 if(A[tag1] >= B[tag2])
25                 {
26                     A[i] = A[tag1];
27                     tag1--;
28                 }
29                 else
30                 {
31                     A[i] = B[tag2];
32                     tag2--;
33                 }
34             }
35         }
36     }
37 };

 

posted on 2013-03-01 14:04  CoderJesse  阅读(116)  评论(0)    收藏  举报