[lintcode easy]Merge Sorted Array II

Merge Sorted Array II

 

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?

///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;
    }
}

 

posted on 2015-11-25 05:26  一心一念  阅读(170)  评论(0编辑  收藏  举报

导航