6. 合并排序数组 II

6. Merge Two Sorted Arrays

Description

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?

public class Solution {
    /**
     * @param A: sorted integer array A
     * @param B: sorted integer array B
     * @return: A new sorted integer array
     */
    public int[] mergeSortedArray(int[] A, int[] B) {
        int i = 0;
        int j = 0;
        int k = 0;
        int[] result = new int[A.length + B.length];
        while(i < A.length && j < B.length){
            if(A[i] <= B[j]){
                result[k++] = A[i];
                i++;
            }else{
                result[k++] = B[j];
                j++;
            }    
        }
        if(i == A.length){
            for(int l = j; l < B.length; l++){
                result[k++] = B[l];
            }
        }else{
            for(int m = i ; m < A.length; m++){
                result[k++] = A[m];
            }
        }
        return result;
    }
}
class Solution {
    /**
     * @param A: sorted integer array A
     * @param B: sorted integer array B
     * @return: A new sorted integer array
     */
    public int[] mergeSortedArray(int[] A, int[] B) {
        // write your code here
        if (A.length == 0 || A == null){
            return B;
        }
        if (B.length == 0 || B == null){
            return A;
        }
        
        int len = A.length + B.length;
        int[] res  = new int[len];
        
        
        if(A.length >= B.length) {
            for(int i=0;i<A.length;i++) {
                res[i] = A[i];
            }
            
            for(int i=0;i<B.length;i++) {
                res[A.length + i] = B[i];
            }
            
        }else {
            for(int i=0;i<B.length;i++) {
                res[i] = B[i];
            }
            
            for(int i=0;i<A.length;i++) {
                res[B.length + i] = A[i];
            }
        }
       Arrays.sort(res);
       return res;
    }
}
描述
合并两个排序的整数数组A和B变成一个新的数组。

您在真实的面试中是否遇到过这个题?  
样例
给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]

转载于:https://www.cnblogs.com/browselife/p/10645541.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值