慕容3067478
Go 旨在鼓励高效的代码。由于排序,您的算法是 O(n log n)。更好的算法是 O(n)。例如,O(n),package mainimport ( "fmt")func TwoOldestAges(ages []int) [2]int { var old [2]int for _, age := range ages { if old[0] < age { old[1] = old[0] old[0] = age } else if old[1] < age { old[1] = age } } return old}func main() { ages := []int{1, 99, 42, 7, 66, 77} fmt.Println(ages) oldest := TwoOldestAges(ages) fmt.Println(oldest) ages = []int{1, 77, 42, 7, 66, 99} fmt.Println(ages) oldest = TwoOldestAges(ages) fmt.Println(oldest)}游乐场: https: //play.golang.org/p/rq4SMS3MRqY输出:[1 99 42 7 66 77][99 77][1 77 42 7 66 99][99 77]