본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 55] Jump Game

by m2162003 2020. 10. 10.

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;
    }
};

댓글