给定两个数组
int arr1[n]
int arr2[m]
哪里 n > m
需要将两个数组的并集写成一个。
例如,如果输入数组是:
int arr1[] = {1, 3, 4, 5, 7}
int arr2[] = {2, 3, 5, 6}
然后程序应该创建新数组 Union 作为 {1, 2, 3, 4, 5, 6, 7}
可以使用 C# 或 Java 实现。
为了解决它,首先需要使用合并排序对数组进行排序 然后做联合
我在网上找了找也没找到优雅的方法。我看过的每一个代码 充满了 IF。
请指教什么是最快速、最优雅的方法
最佳答案
您是正确的,如 Merge Sort 中所做的那样合并两个列表。是最有效率的事情。这假定这两个列表已经排序,如您的示例所示。下面是如何实现合并的示例:
function merge(left,right)
var list result
while length(left) > 0 or length(right) > 0
if length(left) > 0 and length(right) > 0
if first(left) ≤ first(right)
append first(left) to result
left = rest(left)
else
append first(right) to result
right = rest(right)
else if length(left) > 0
append first(left) to result
left = rest(left)
else if length(right) > 0
append first(right) to result
right = rest(right)
end while
return result
从这里开始,只需不在最终输出中包含重复即可。
关于c# - 两个数组的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8406582/