我正在查看其中一个问题 How to merge two sorted arrays ,并努力使用 Java 8 流转换解决方案。但仍然没有成功。实际上,我没有什么可以在这里分享的。
必须有一种方法可以在函数式编程中使用索引来处理此类循环。在不改变时间复杂度的情况下,如何用其他语言(如 Scala、Clojure)做到这一点?也许那时我可以尝试用 Java 复制它。
编辑:提到问题的代码是最有效的,我不想妥协。
最佳答案
事实上,到处都有相同的方法:您重复两个集合,将最少的集合头添加到结果中,然后与其余集合一起重复,直到其中一个集合(或两个集合)为空。在 Clojure 中:
(defn merge-sorted [pred coll1 coll2]
(loop [coll1 coll1 coll2 coll2 res []]
(cond (or (empty? coll1) (empty? coll2)) (concat res coll1 coll2)
(pred (first coll1) (first coll2)) (recur (rest coll1)
coll2
(conj res (first coll1)))
:else (recur coll1 (rest coll2) (conj res (first coll2))))))
user> (merge-sorted < [1 3 5 6 7 8 9 40 50] [1 2 5 10 100])
(1 1 2 3 5 5 6 7 8 9 10 40 50 100)
关于java - 使用函数式风格合并两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38866350/