博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
两个有序的数组,合并成一个有序的数组
阅读量:3731 次
发布时间:2019-05-22

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

/** * 两个有序的数组,合并成一个有序的数组 * @author ccq * */public class Test1 {	public static void main(String[] args) {		int[] a = new int[] { 1, 3, 5, 7, 8, 8, 9, 100, 111, 222 };		int[] b = new int[] { 2, 3, 4, 5, 6, 7, 8 };		int arr[] = sortArr(a, b);		for (int i = 0; i < arr.length; i++) {			System.out.print(arr[i] + " ");		}	}	/**	 * 算法复杂度O(m+n)	 * m : a数组的长度	 * n : b数组的长度	 * @param a	 * @param b	 * @return arr 合并后的数组	 */	public static int[] sortArr(int[] a, int[] b) {				int sum = 0;				int aIndex = 0;		int bIndex = 0;		int arrIndex = 0;				int aLen = a.length;		int bLen = b.length;		int[] arr = new int[aLen + bLen];		while (aIndex < aLen && bIndex < bLen) {			if (a[aIndex] < b[bIndex]) {				arr[arrIndex++] = a[aIndex++];			}else if(a[aIndex] == b[bIndex]){				arr[arrIndex++] = a[aIndex++];				arr[arrIndex++] = b[bIndex++];			}else {				arr[arrIndex++] = b[bIndex++];			}						sum++;		}		for (int i = aIndex; i < aLen; i++) {			arr[arrIndex++] = a[i];			sum++;		}		for (int i = bIndex; i < bLen; i++) {			arr[arrIndex++] = b[i];			sum++;		}				System.out.println("sum = " + sum + ", a+b = " + (aLen + bLen));		return arr;	}}

转载地址:http://ggzin.baihongyu.com/

你可能感兴趣的文章
IO流
查看>>
网络编程
查看>>
事务与索引
查看>>
Carp后端开发文档
查看>>
Redis
查看>>
后端开发文档
查看>>
JVM自动内存管理
查看>>
http
查看>>
https
查看>>
Java并发线程池原理解析
查看>>
深度讲解微服务架构中的负载均衡算法
查看>>
MySQL索引~B+树原理解析
查看>>
分布式事务系列一:BASE,一种ACID的替代方案(eBay分布式事务解决方案)
查看>>
分布式事务系列二:TCC
查看>>
分布式事务系列三:Saga
查看>>
分布式常见面试题整理
查看>>
Java虚拟机之内存模型
查看>>
Django-rest-framework简单使用
查看>>
Django REST Framework提供的视图
查看>>
Django REST Framework之视图
查看>>