题意:

image.png

解题思路:

  1. 贪心: 本题是对下一步跳法的一种贪心算法,比如2,可以跳到31,但是3又能跳更远的距离,所以跳3
  2. max: 当前路径能跳的最远距离 {2 3 1 1 4}:2能挑到1,但是路径中有3,所以最远距离max = 4
  3. can_arrived:实际最远能跳的距离,能跳到的距离
  4. 0 1 2 3 4
  5. 2 3 1 1 4
  6. $i = 0 max = 2 //当前能跳到下标为2的位置
  7. $i = 1 step = 1 can_arrived = 2 max = 4
  8. $i = 2 max = 4
  9. $i = 3 step = 2 can_arrived = 4
  10. $i = 4 max = 8

PHP代码实现:

  1. class Solution {
  2. function jump($nums) {
  3. $step = 0;
  4. $can_arrived = 0;
  5. $max = 0;
  6. for ($i = 0; $i < count($nums); $i++) {
  7. if ($can_arrived < $i) {
  8. $step++;
  9. $can_arrived = $max;
  10. }
  11. $max = max($max, $i + $nums[$i]);
  12. }
  13. return $step;
  14. }
  15. }

GO代码实现:

  1. func jump(nums []int) int {
  2. step := 0
  3. can_arrived := 0
  4. maxPosition := 0
  5. for i := 0; i < len(nums); i++ {
  6. if can_arrived < i {
  7. step++
  8. can_arrived = maxPosition
  9. }
  10. maxPosition = max(maxPosition, i + nums[i])
  11. }
  12. return step
  13. }
  14. func max(x, y int) int {
  15. if x > y {
  16. return x
  17. }
  18. return y
  19. }