|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | +) |
| 6 | + |
| 7 | +// https://medium.com/@william31525/leetcode-45-jump-game-2-294a21f5baba |
| 8 | +func jump(nums []int) int { |
| 9 | + if len(nums) <= 2 { |
| 10 | + return len(nums) - 1 |
| 11 | + } |
| 12 | + |
| 13 | + var footprints []int |
| 14 | + for { |
| 15 | + lastStep := -1 |
| 16 | + for i := 0; i < len(nums); i++ { |
| 17 | + if i + nums[i] >= len(nums) - 1 { |
| 18 | + lastStep = i |
| 19 | + footprints = append(footprints, lastStep) |
| 20 | + break |
| 21 | + } |
| 22 | + } |
| 23 | + if lastStep == 0 { |
| 24 | + break |
| 25 | + } |
| 26 | + nums = nums[:lastStep+1] |
| 27 | + } |
| 28 | + return len(footprints) |
| 29 | +} |
| 30 | + |
| 31 | +func max(a, b int) int { |
| 32 | + if a > b { |
| 33 | + return a |
| 34 | + } |
| 35 | + return b |
| 36 | +} |
| 37 | + |
| 38 | +func jump2(nums []int) int { |
| 39 | + if len(nums) <= 2 { |
| 40 | + return len(nums) - 1 |
| 41 | + } |
| 42 | + |
| 43 | + farest := 0 |
| 44 | + end := 0 |
| 45 | + step := 0 |
| 46 | + |
| 47 | + for i := 0; i < len(nums); i++ { |
| 48 | + farest = max(farest, i+nums[i]) |
| 49 | + if i == end { |
| 50 | + end = farest |
| 51 | + step++ |
| 52 | + } |
| 53 | + if end >= len(nums) - 1 { |
| 54 | + break |
| 55 | + } |
| 56 | + } |
| 57 | + return step |
| 58 | +} |
| 59 | + |
| 60 | + |
| 61 | +func main() { |
| 62 | + fmt.Println(jump([]int{2,3,1,1,4})) |
| 63 | + fmt.Println(jump([]int{1,1,1,1,1})) |
| 64 | + fmt.Println(jump([]int{3,1,0})) |
| 65 | + fmt.Println(jump([]int{2,3,1})) |
| 66 | + fmt.Println(jump([]int{2,3,1,4})) |
| 67 | + fmt.Println(jump([]int{2,3,1,1,4})) |
| 68 | + |
| 69 | + fmt.Println("===") |
| 70 | + |
| 71 | + fmt.Println(jump2([]int{2,3,1,1,4})) |
| 72 | + fmt.Println(jump2([]int{1,1,1,1,1})) |
| 73 | + fmt.Println(jump2([]int{3,1,0})) |
| 74 | + fmt.Println(jump2([]int{2,3,1})) |
| 75 | + fmt.Println(jump2([]int{2,3,1,4})) |
| 76 | + fmt.Println(jump2([]int{2,3,1,1,4})) |
| 77 | +} |
0 commit comments