本文主要是介绍java常用算法之两个有序list的合并,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*** 两个已顺序排序数组的合并* * @param aList* @param bList* @return*/public static List<Integer> mergeTwoSortList(List<Integer> aList,List<Integer> bList) {int aLength = aList.size(), bLength = bList.size();List<Integer> mergeList = new ArrayList();int i = 0, j = 0;while (aLength > i && bLength > j) {if (aList.get(i) > bList.get(j)) {mergeList.add(i + j, bList.get(j));j++;} else {mergeList.add(i + j, aList.get(i));i++;}}// blist元素已排好序, alist还有剩余元素while (aLength > i) {mergeList.add(i + j, aList.get(i));i++;}// alist元素已排好序, blist还有剩余元素while (bLength > j) {mergeList.add(i + j, bList.get(j));j++;}return mergeList;}public static void main(String[] args) {List<Integer> aList = new ArrayList();aList.add(3);aList.add(6);aList.add(7);aList.add(10);aList.add(13);List<Integer> bList = new ArrayList();bList.add(1);bList.add(2);bList.add(5);bList.add(12);bList.add(15);bList.add(20);bList.add(21);List<Integer> mergeList = mergeTwoSortList(aList, bList);System.err.println(mergeList.toString());}
输出结果如下:
[1, 2, 3, 5, 6, 7, 10, 12, 13, 15, 16, 17, 20, 21, 22]
这篇关于java常用算法之两个有序list的合并的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!