[JS] Jump Game
2022. 9. 4. 13:30
🔒 문제 (LeetCode 55)
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Constraints:
- 1 <= nums.length <= 104
- 0 <= nums[i] <= 105
🌊 입출력
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 jump length is 0, which makes it impossible to reach the last index.
🔑 해결
🌌 알고리즘 - Greedy
/**
* @param {number[]} nums
* @return {boolean}
*/
var canJump = function(nums) {
let cur = 0
for(let i = 0; i < nums.length; i++) {
if(i > cur) return false
cur = Math.max(cur, i + nums[i])
}
return true
};
'코딩테스트 (JS) > ETC' 카테고리의 다른 글
[JS] Happy Number (0) | 2022.09.28 |
---|---|
[JS] Shuffle an Array (0) | 2022.09.28 |
[JS] Single Number (0) | 2022.08.03 |
[JS] Reverse Bits (0) | 2022.08.03 |
[JS] Number of 1 Bits (0) | 2022.08.02 |