题目:给定两个有序数组,将其合并为一个有序数组。
思路:采纳双指针的形式,顺次遍历两个数组 a,b。而后比照两个数组各个地位的元素,a小于b,则将a的元素存入新数组,而后a的指针加1,a==b,则将两个元素都放入新数组,下标都加1,如果a大于b,则将b的元素放入新数组,而后b的指针加1。
代码
go
func combine(a, b []int) { left,right := 0,0 lena,lenb := len(a),len(b) res := make([]int, 0) for { if left == lena { res = append(res, b[right:]...) break } if right == lenb { res = append(res, a[left:]...) break } if a[left] < b[right] { res = append(res, a[left]) left++ } else if a[left] == b[right] { res = append(res, []int{a[left], b[right]}...) left++ right++ } else { res = append(res, b[right]) right++ } } fmt.Println(res)}
php
function test($a, $b):array { $lena = count($a); $lenb = count($b); $res = []; $left = $right = 0; while ($left < $lena && $right < $lenb) { if ($a[$left] < $b[$right]) { $res[] = $a[$left]; $left++; } else if ($a[$left] == $b[$right]) { $res[] = $a[$left]; $res[] = $b[$right]; $left++; $right++; } else { $res[] = $b[$right]; $right++; } } if ($left == $lena) { $res = array_merge($res, array_slice($b, $right)); } if ($right == $lenb) { $res = array_merge($res, array_slice($a, $left)); } return $res;}