标签:
Merge Sorted Array II
Merge two given sorted integer array A and B into a new sorted integer array.
A=[1,2,3,4]
B=[2,4,5,6]
return [1,2,2,3,4,4,5,6]
How can you optimize your algorithm if one array is very large and the other is very small?
///same as Merge Sorted Array
///in Java , the function to get items in arraylist is to use array.get(i) and the length of an array is array.size();
///in C#, the length of an arraylist is array.count , the items in arraylist is array[i];
class Solution { /** * @param A and B: sorted integer array A and B. * @return: A new sorted integer array */ public ArrayList<Integer> mergeSortedArray(ArrayList<Integer> A, ArrayList<Integer> B) { // write your code here ArrayList<Integer> res=new ArrayList<Integer>(); int m=A.size(); int n=B.size(); int i=0,j=0; while(i<m && j<n) { if(A.get(i)<B.get(j)) { res.add(A.get(i)); i++; } else { res.add(B.get(j)); j++; } } while(i<m) { res.add(A.get(i)); i++; } while(j<n) { res.add(B.get(j)); j++; } return res; } }
[lintcode easy]Merge Sorted Array II
标签:
原文地址:http://www.cnblogs.com/kittyamin/p/4993515.html