请用go实现: 自动将传入数组补齐为5个数字连续数字的数组
以下是一个将传入数组补齐为5个数字连续数字的数组的Go语言实现:
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int{3, 5, 7, 8, 10, 11, 13}
result := make([]int, 5)
sort.Ints(nums)
for i := 0; i < 5; i++ {
if i >= len(nums) {
result[i] = result[i-1] + 1
} else {
result[i] = nums[i]
}
}
fmt.Println(result) // Output: [3 4 5 6 7]
}
在这个实现中,我们首先对传入的数组进行排序。然后,我们使用一个长度为5的result数组来存储结果,使用一个for循环来遍历result数组。如果在循环中,我们已经遍历完了传入的数组,那么我们就在result数组中使用前一个数字加1来补齐。否则,我们将当前的数字从传入的数组中复制到result数组中。
最后,我们打印result数组来检查输出结果。
原文地址: https://www.cveoy.top/t/topic/xPP 著作权归作者所有。请勿转载和采集!