[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.

给定两个有序数组A和B,将B中的元素插入A(假设A有足够大的空间),保持有序性

Tip: A和B的大小已知,即合并完成后的数组大小确定。

将指针指向A和B的尾端,从数组的尾端(最大值)处开始合并。若B中仍有剩余元素,全部插入A的头部。

代码

 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         if(B==NULL || n==0)
 6             return;
 7         
 8         int p=m-1, q=n-1, cur=m+n-1;
 9         while(p>=0 && q>=0)
10         {
11             if(A[p]>=B[q])
12             {
13                 A[cur--] = A[p--];
14             }
15             else
16             {
17                 A[cur--] = B[q--];
18             }
19         }
20         while(q>=0)
21             A[cur--] = B[q--];
22     }
23 };

 

posted @ 2013-10-27 22:57  Apprentice.Z  阅读(132)  评论(0编辑  收藏  举报