码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Sorted Array

时间:2016-07-01 11:33:37      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

Given two sorted integer arrays A and B, merge B into A as one sorted array.

 Notice

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 are m and n respectively.

Example

A = [1, 2, 3, empty, empty], B = [4, 5]

After merge, A will be filled as [1, 2, 3, 4, 5]

分析:

这题的确很简单,用两个pointer分别指向两个array的最后一个数,然后根据它们的大小依次把它们添加到array A里(从末到头添加)

 1 class Solution {
 2     /**
 3      * @param A: sorted integer array A which has m elements, 
 4      *           but size of A is m+n
 5      * @param B: sorted integer array B which has n elements
 6      * @return: void
 7      * cnblogs.com/beiyeqingteng/
 8      */
 9     public void mergeSortedArray(int[] A, int m, int[] B, int n) {
10         if (n <= 0) return;
11         if (m < 0) return;
12         
13         int pa = m - 1;
14         int pb = n - 1;
15         
16         int p = m + n - 1;
17         
18         while (pa >= 0 & pb >= 0) {
19             if (A[pa] >= B[pb]) {
20                 A[p] = A[pa];
21                 pa--;
22             } else {
23                 A[p] = B[pb];
24                 pb--;
25             }
26             p--;
27         }
28         
29         while (pa >= 0) {
30             A[p] = A[pa];
31             pa--;
32             p--;
33         }
34         
35         while (pb >= 0) {
36             A[p] = B[pb];
37             pb--;
38             p--;
39         }
40     }
41 }

转载请注明出处:cnblogs.com/beiyeqingteng/

Merge Sorted Array

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5632262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!