我们有一个锅铲和一堆煎饼,我们的目标是将煎饼按照大小排序,大的在下面。我们唯一的办法是让锅铲从一个地方伸进去,并且把上面所有的煎饼翻下来。
Go实现:
package main
import (
"fmt"
)
func main() {
var stact = []int{1, 4, 5, 2, 3, 8, 6, 7, 9, 0}
cakeNum := len(stact)
for i := 0; i < cakeNum; i++ {
biggest := biggestPancake(stact, cakeNum-i)
updata := flip(stact, biggest)
stact = flip(updata, cakeNum-i-1)
}
fmt.Print(stact)
}
func flip(arr []int, i int) []int {
up := arr[:i+1]
down := arr[i+1:]
var newArr []int
for i := len(up) - 1; i >= 0; i-- {
newArr = append(newArr, up[i])
}
for n := 0; n < len(down); n++ {
newArr = append(newArr, down[n])
}
return newArr
}
//获取前count位最大的值
func biggestPancake(arr []int, count int) int {
var max = 0
var maxIndex = 0
for j := 0; j < count; j++ {
if arr[j] > max {
max = arr[j]
maxIndex = j
}
}
return maxIndex
}
网友评论