是的,它可以做到,实际上它是O(n + m),其中 n 和 m 是第一个和第二个数组的长度,连续。
该算法称为一次通过合并
伪代码:
i, j, k = 0 // k is index for resulting array
//maximum length of the resulting array can be n+m,
//so it is always safe to malloc for such a length if you are in C or C++
while(i< len(array1) and j < len(array2) )
if (array1[i] == array2[j])
result[k] = array1[i]
++i, ++j, ++k
else if (array1[i] < array2[j])
result[k] = array1[i]
++i, ++k
else
result[k] = array2[j]
++j, ++k
//now one array might not be traversed all the way up
if ( i < len(array1) )
while( i != len(array1))
result[k] = array1[i]
++i, ++k
else if ( j < len(array2) )
while( j != len(array2) )
result[k] = array2[j]
++j, ++k
基本上,您同时遍历两个数组,如果长度不同,则不会一直遍历较大的数组,因此您只需将较大数组的所有元素添加到结果中。