有没有可以合并两个排序数组的实用程序?

我想知道是否有一些实用程序(库)可以在 1 行中合并两个排序数组。


繁华开满天机
浏览 123回答 2
2回答

千万里不及你

CollectionUtils.collate从 Apache Commons使用。从文档:将两个已排序的集合 a 和 b 合并到一个已排序的列表中,以便保留元素的自然顺序。使用标准的 O(n) 合并算法来组合两个排序列表。这是一个例子import static java.util.Arrays.asList;import java.util.List;import org.apache.commons.collections4.CollectionUtils;public class MergeSortedArrays {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Integer a[] = new Integer[]{2, 4, 6, 8, 10};&nbsp; &nbsp; &nbsp; &nbsp; Integer b[] = new Integer[]{1, 3, 4, 5, 6};&nbsp; &nbsp; &nbsp; &nbsp; List<Integer> merged = CollectionUtils.collate(asList(a), asList(b));&nbsp; &nbsp; }}该库还提供了一些更有用的重载// 1. discards duplicatesstatic <O extends Comparable<? super O>> List<O> collate(Iterable<? extends O> a, Iterable<? extends O> b, boolean includeDuplicates)// 2. uses a custom comparatorstatic <O> List<O> collate(Iterable<? extends O> a, Iterable<? extends O> b, Comparator<? super O> c)// 3. uses a custom comparator and discards duplicatesstatic <O> List<O> collate(Iterable<? extends O> a, Iterable<? extends O> b, Comparator<? super O> c, boolean includeDuplicates)

月关宝盒

创建一个简单的合并函数不是比为这样一个简单的任务添加一个完整的库更好吗?你有 array1(0,1,2,2,3,4) 和 array2(0,2,4,5) 和一个 returnArray 查看前 2 个值并选择最低的,如果它们相同,选择 array1将该值添加到 returnArray。继续从选择的数组中删除该值重复过程直到合并您可以只增加一个整数而不是删除效率问题。编辑哎呀,没想到你已经知道归并排序了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java