給定兩個已遞增排序的陣列,將其合併為一個新的有序陣列。這是經典的「合併排序」核心步驟,也是常見面試題。關鍵在於利用「已排序」特性,以 O(m+n) 時間複雜度完成,避免重新排序的 O((m+n) log(m+n))。
function mergeSortedArrays(array $a, array $b): array {
$result = [];
$i = $j = 0;
$lenA = count($a);
$lenB = count($b);
while ($i < $lenA && $j < $lenB) {
if ($a[$i] <= $b[$j]) {
$result[] = $a[$i++];
} else {
$result[] = $b[$j++];
}
}
// 附加剩餘元素
while ($i < $lenA) $result[] = $a[$i++];
while ($j < $lenB) $result[] = $b[$j++];
return $result;
}
// 測試
$a = [1, 2, 3, 4, 5, 6];
$b = [2, 3, 4, 10, 10, 10, 10];
print_r(mergeSortedArrays($a, $b));
/* 結果:
Array (
[0] => 1 [1] => 2 [2] => 2 [3] => 3 [4] => 3 [5] => 4
[6] => 4 [7] => 5 [8] => 6 [9] => 10 [10] => 10 [11] => 10 [12] => 10
) */
def merge_sorted(a, b):
i = j = 0
result = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
result.append(a[i]); i += 1
else:
result.append(b[j]); j += 1
result.extend(a[i:])
result.extend(b[j:])
return result
print(merge_sorted([1,2,3,4,5,6], [2,3,4,10,10,10,10]))
#include#include int* merge_sorted(const int* a, int len_a, const int* b, int len_b, int* out_len) { int* result = malloc((len_a + len_b) * sizeof(int)); int i = 0, j = 0, k = 0; while (i < len_a && j < len_b) { result[k++] = (a[i] <= b[j]) ? a[i++] : b[j++]; } while (i < len_a) result[k++] = a[i++]; while (j < len_b) result[k++] = b[j++]; *out_len = k; return result; } int main() { int a[] = {1,2,3,4,5,6}; int b[] = {2,3,4,10,10,10,10}; int len; int* c = merge_sorted(a, 6, b, 7, &len); for (int i = 0; i < len; i++) printf("%d ", c[i]); free(c); return 0; }
package main
import "fmt"
func mergeSorted(a, b []int) []int {
result := make([]int, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
result = append(result, a[i]); i++
} else {
result = append(result, b[j]); j++
}
}
result = append(result, a[i:]...)
result = append(result, b[j:]...)
return result
}
func main() {
a := []int{1,2,3,4,5,6}
b := []int{2,3,4,10,10,10,10}
fmt.Println(mergeSorted(a, b))
}
| 語言 | 時間複雜度 | 空間複雜度 | 備註 |
|---|---|---|---|
| PHP | O(m+n) | O(m+n) | 避免 array_shift(O(n)),改用索引 |
| Python | O(m+n) | O(m+n) | extend 切片為 C 層實作,極快 |
| C | O(m+n) | O(m+n) | 手動記憶體管理,零開銷 |
| Go | O(m+n) | O(m+n) | 切片擴容策略優秀,適合高併發 |
function mergeSortedOptimized(array $a, array $b): array {
$result = [];
$resultCount = 0;
$i = $j = 0;
$lenA = count($a);
$lenB = count($b);
// 預分配記憶體(PHP 7.1+)
$result = array_pad([], $lenA + $lenB, null);
while ($i < $lenA && $j < $lenB) {
$result[$resultCount++] = ($a[$i] <= $b[$j]) ? $a[$i++] : $b[$j++];
}
while ($i < $lenA) $result[$resultCount++] = $a[$i++];
while ($j < $lenB) $result[$resultCount++] = $b[$j++];
return $result; // 已為連續索引陣列
}