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

Lintcode: Merge Sorted Array

时间:2015-03-16 06:11:42      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

Merge two given sorted integer array A and B into a new sorted integer array.

Example
A=[1,2,3,4]

B=[2,4,5,6]

return [1,2,2,3,4,4,5,6]

Challenge
How can you optimize your algorithm if one array is very large and the other is very small?

没什么好说的,Arraylist来做merge, 建一个新ArrayList

 1 class Solution {
 2     /**
 3      * @param A and B: sorted integer array A and B.
 4      * @return: A new sorted integer array
 5      */
 6     public ArrayList<Integer> mergeSortedArray(ArrayList<Integer> A, ArrayList<Integer> B) {
 7         // write your code here
 8         if (A==null || A.size()==0) return B;
 9         if (B==null || B.size()==0) return A;
10         ArrayList<Integer> res = new ArrayList<Integer>();
11         int i=0, j=0;
12         for (int k=0; k<A.size()+B.size(); k++) {
13             if (i<A.size() && j<B.size() && A.get(i) < B.get(j)) {
14                 res.add(A.get(i));
15                 i++;
16             }
17             else if (i<A.size() && j<B.size() && A.get(i) >= B.get(j)){
18                 res.add(B.get(j));
19                 j++;
20             }
21             else if (i<A.size()) {
22                 res.add(A.get(i));
23                 i++;
24             }
25             else {
26                 res.add(B.get(j));
27                 j++;
28             }
29         }
30         return res;
31     }
32 }

 

Lintcode: Merge Sorted Array

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4340934.html

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