Skip to content

Instantly share code, notes, and snippets.

@ufo22940268
Created April 28, 2021 11:11
Show Gist options
  • Save ufo22940268/687299d4dbef58cc76c5079bcc2edceb to your computer and use it in GitHub Desktop.
Save ufo22940268/687299d4dbef58cc76c5079bcc2edceb to your computer and use it in GitHub Desktop.
//Given an array of non-negative integers nums, you are initially positioned at
//the first index of the array.
//
// Each element in the array represents your maximum jump length at that positio
//n.
//
// Determine if you are able to reach the last index.
//
//
// Example 1:
//
//
//Input: nums = [2,3,1,1,4]
//Output: true
//Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
//
//
// Example 2:
//
//
//Input: nums = [3,2,1,0,4]
//Output: false
//Explanation: You will always arrive at index 3 no matter what. Its maximum jum
//p length is 0, which makes it impossible to reach the last index.
//
//
//
// Constraints:
//
//
// 1 <= nums.length <= 3 * 104
// 0 <= nums[i] <= 105
//
// Related Topics 贪心算法 数组
// 👍 1169 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* @param {number[]} nums
* @return {boolean}
*/
var canJump = function (nums) {
let stack = [0];
const visited = new Array(nums.length).fill(false);
while (stack.length) {
const index = stack.pop();
if (visited[index]) {
continue;
}
visited[index] = true;
if (index == nums.length - 1) return true;
for (let i = 1; i <= nums[index]; i++) {
if (index + i < nums.length) {
stack.push(index + i);
}
}
}
return false;
};
//leetcode submit region end(Prohibit modification and deletion)
const r = canJump([2, 3, 1, 1, 4])
console.log(`r: ` + JSON.stringify(r, null, 4) + '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment