LeetCode 55. Jumping game (greedy)-JavaScript

Question link: https://leetcode-cn.com/problems/jump-game/


Title description:


Problem-solving ideas:

For the element at position i, the farthest position it can jump to is i + nums[i]. If the farthest position of an element jumps beyond or equal to the position at the end of the array, it returns true.

That is, we traverse the array elements in turn and maintain a furthest position in real time. For the current traversed element, if the element is in the furthest position, it means that the element is reachable.


Code:

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var canJump = function(nums) {
    if (nums.length == 1) {
        return true;
    }
    let maxStep;
    maxStep = nums[0];
    for (let i = 1; i < nums.length; i++) {
        if (maxStep >= nums.length - 1) {
            return true;
        }
        if (i <= maxStep && i + nums[i] > maxStep) {
            maxStep = i + nums[i];
        }
    }
    return false;
};

Time complexity: O(n)

Space complexity: O(1)

Guess you like

Origin blog.csdn.net/ySFRaabbcc/article/details/110817084