Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
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 jump length is 0, which makes it impossible to reach the last index.
- 백준의 계단 문제와 유사한 느낌?? 다시 봐야 겠다
- 과눈이의 풀이 : 뒤에서부터 확인한다.
- 위치 i에서 max 스텝이 현재 위치에 도달할 수 있다면 true
- 마지막에 저장된 인덱스가 0에 도달하면 true를 리턴
class Solution {
public:
bool canJump(vector<int>& nums) {
int reachableIndex = nums.size() - 1;
int lastIdx = nums.size()-1;
for(int i=nums.size()-1; i>=0; i--){
if(i + nums[i] >= reachableIndex){
reachableIndex = i;
}
}
if(reachableIndex != 0){
return false;
}
return true;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 543] Diameter of Binary Tree (0) | 2020.10.11 |
---|---|
[leetcode 617] Merge Two Binary Trees (0) | 2020.10.11 |
[leetcode 406] Queue Reconstruction by Height (0) | 2020.10.10 |
[leetcode 763] Partition Labels (0) | 2020.10.10 |
[leetcode 221] Maximal Square (0) | 2020.10.08 |
댓글