飘落的树叶

导航

[LeetCode]Merge Sorted Array

Description:

 

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 (size that is greater or equal to m +n) to hold additional elements from B. The number of elements initialized in A and B arem and n respectively.

 

描述:

给出A和B两个已经排好序的整数数组(从小到大排序),把B整合入A中,让整合后的数组也是排好序的。另外,A有足够多的空间来存储数据(即A的长度大于等于m+n,m和n为两个数组所包含数据的大小)。

 

解答:

归并排序的步骤之一。只用两个数组可以节省空间。至于节省时间的方法,就是我们要想的答案了。从尾部开始排序——哪一个数据大,就先放到尾部。其余的部分就和大家熟悉的归并排序一样了。但是这道题注意边界条件。

C++代码:

 1 class Solution {
 2 public:
 3     void merge(int A[], int m, int B[], int n)
 4     {
 5         if(m == 0) {
 6             for(int j = 0; j < n; j++) A[j] = B[j];
 7             return;
 8         }
 9         
10         if(n == 0) {
11             return;
12         }
13         
14         int index = m + n - 1;
15         int i = m - 1;
16         int j = n - 1;
17         
18         while(i >= 0 && j >= 0) {
19             if( A[i] > B[j] ) {
20                 A[index] = A[i];
21                 i--;
22                 index--;
23             } else {
24                 A[index] = B[j];
25                 j--;
26                 index--;
27             }
28         }
29         
30         while(i >= 0) {
31             A[index] = A[i];
32             i--;
33             index--;
34         }
35         
36         while(j >= 0) {
37             A[index] = B[j];
38             j--;
39             index--;
40         }
41     }
42 };

 

posted on 2014-06-13 15:03  飘落的树叶  阅读(109)  评论(0)    收藏  举报