博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
6. 合并排序数组 II
阅读量:4557 次
发布时间:2019-06-08

本文共 1761 字,大约阅读时间需要 5 分钟。

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和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

你可能感兴趣的文章
DLL远程注入与卸载
查看>>
Jmeter-ForEach控制器
查看>>
Checklist: 2019 05.01 ~ 06.30
查看>>
Binary XML file : Error inflating class com.esri.android.map.MapView
查看>>
grep,awk和sed
查看>>
.NET Core WebAPI IIS 部署问题
查看>>
SystemTap 静态探针安装包
查看>>
redis五种数据类型的使用
查看>>
Form表单中的onClick,onSubmit和submit
查看>>
Python-SocketServer源码
查看>>
JavaScript-基本数据类型
查看>>
CentOS 7.3 实体机启动 U 盘制作
查看>>
mysql数据库
查看>>
dede调用文章里的图片
查看>>
windows 窗体基本控件
查看>>
unix date 命令获取某日期的前一天
查看>>
python中set、list、dict内部实现原理
查看>>
Python3 MySQL 数据库连接
查看>>
正则\1\2和\\1的理解
查看>>
Python文件操作(一)
查看>>