package main
import (
"fmt"
)
func mergeAB(a, b []int) []int {
lenA := len(a)
lenB := len(b)
ab := make([]int, lenA+lenB)
index := 0
//从首元素开始,将较小的放入到新切片中,再将较小的数组下标加一
i, j := 0, 0
for i, j = 0, 0; i < lenA && j < lenB; {
if a[i] < b[j] {
ab[index] = a[i]
index++
i++
} else if a[i] > b[j] {
ab[index] = b[j]
index++
j++
} else {
ab[index] = a[i]
index++
i++
}
}
//一定有一个数组是先遍历完,把另外一个数组的所有元素都添加进去
for i < lenA {
ab[index] = a[i]
i++
index++
}
for j < lenB {
ab[index] = b[j]
j++
index++
}
fmt.Println("你好")
return ab
}
func main() {
var ab []int
var a = []int{1, 5, 7, 10}
var b = []int{2, 6, 9, 13, 19, 90}
ab = mergeAB(a, b)
fmt.Println(ab)
fmt.Println("happy")
}
输出显示
golang 合并两个有序的数组(笔试题)
代码如下