Original link: leetcode-cn.com/problems/ju…

Answer:

  1. You don’t really need to simulate a jump, but you need to know how far you can jump from the first point.
  2. Such as traversal,3,1,1,4 [2]:
    • We can jump from index 0 to 2(0+2) at most, so that 0~2 are in the reachable range.
    • Up to 4(1+3) can be reached from index 1, which is the last position.
  3. Such as traversal,2,1,0,4 [3]:
    • We can jump from index 0 to 3(0+3) at most, so that 0~3 are in the reachable range.
    • You can jump from 1 to 3(1+2) at most, and from 2 to 3(2+1) at most. You cannot continue jumping from 3.
    • So if you jump from 0, the most you can get to is 3, and you’ll never get to 4.
    • By the time the loop reaches 4, the current index has exceeded the maximum reachable position 3, which means it can no longer move forward, and all positions after 4 are unreachable.
/ * * *@param {number[]} nums
 * @return {boolean}* /
var canJump = function(nums) {
  let max = 0 // Store the farthest position that can be reached after going forward

  for (let i = 0; i < nums.length; i++) {
    // If the current position is beyond the farthest position, it means that it is impossible to go from all previous positions to the position I and beyond
    if (i > max) {
      return false
    }

    // Calculate the maximum possible position after nums[I] step forward
    max = Math.max(max, i + nums[i])

    // If the farthest position has reached the last position, you can exit the loop
    if (max >= nums.length - 1) {
      return true}}};Copy the code