https://leetcode-cn.com/problems/jump-game-ii/

三个变量

  • step: 当前最少跳几步能到i
  • cur: 跳的步数不超过step, 最右能到哪
  • next : 跳的步数不超过step + 1步, 最右能到哪

1) i > cur, 说明step步不足以到达i,step++, cur = next

2)i <= cur, 说明step步内能到达i, step不用++, 但要看下next能不能更新变得更大

image.png
跳0步能到0位置,
跳的步数不超过0, 最右能到0位置
跳的步数不超过1, 最右能到3位置
image.png
i来到1,之前0步能到0位置, 现在step = 1, 也就是跳一步能到什么位置,也就是之前算的next=3, 把next的值赋值给cur,

若i ≤ cur, 说明step步内还能到达i, step不用++, 但是要看一下next能不能变得更大

image.png
image.png

  1. public int jump(int[] nums) {
  2. int step = 0;
  3. int cur = 0;
  4. int next = nums[0];
  5. for (int i = 1; i < nums.length; i++) {
  6. if (cur < i) {
  7. step++;
  8. cur = next;
  9. }
  10. next = Math.max(next, i + nums[i]);
  11. }
  12. return step;
  13. }