找两个数组中的相同元素

昨天柯柯问了个,如果有两个数组 a 和 b (没有重复元素),要将 a 和 b 中的中相同的元素放入数组 c 中,不同的元素放入数组 d 中,用什么方法好?

想了一会,只想到先排序,然后再遍历的办法,伪代码如下:

sort a 
sort b
for i=0, j=0 , until i < a.length || j < b.length
    if a[i] == b[j] then
        add a[i] to c
        i++, j++
    if a[i] < b[j] then
        add a[i] to d
        i++
    if a[i] > b[j] then
        add b[j] to d
        j++
if i == a.length then
    add remain of b to d 
else
    add remain of a to d 

不知道还有什么办法能更“快”?(时间复杂度上)

还请路过的大牛们赐教

 

原文地址:https://www.cnblogs.com/muxue/p/1714914.html