Merge Sorted Array [LEETCODE]

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         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         int *C = new int[m+n];
 6         for(int i = 0,  j = 0, k = 0; k < m + n; k++){
 7             if(i >= m){
 8                 C[k] = B[j];
 9                 j++;
10                 continue;
11             }
12             if(j >= n){
13                 C[k] = A[i];
14                 i++;
15                 continue;
16             }
17             if(A[i] <= B[j]){
18                 C[k] = A[i];
19                 i++;
20                 continue;
21             }
22             if(A[i] > B[j]){
23                 C[k] = B[j];
24                 j++;
25                 continue;
26             }
27         }
28         memcpy(A, C, (m + n) * sizeof(int));
29     }
30 };

 

posted @ 2013-10-16 16:29  昱铭  阅读(158)  评论(0)    收藏  举报