[leetcode] Array/String (Medium) - 55. Jump Game

brandon·2025년 5월 22일

leetcode-array/strings

목록 보기
9/20

Intuition 🤔

처음에는 dynamic programming 을 써야할까 생각했다.
하지만 그렇지 않아도 될 것 같다.
현재 step count를 저장해놓고 한칸씩 움직일때마다 하나씩 줄이고, 현재 count보다 현재 위치한 인덱스의 숫자가 더 크다면 그 숫자로 replace하면 될 것 같다.
그리하여 만약 step count가 0이 되고 현재 위치한 인덱스의 숫자도 0이라면 도달할 수 없다.

답안

class Solution {
    public boolean canJump(int[] nums) {
        if (nums.length == 1) {
            return true; 
        }

        int stepLeft = nums[0]; 
        int currentIndex = 0; 
        while (stepLeft > 0 && currentIndex < nums.length - 1) {
            stepLeft -= 1; 
            currentIndex += 1; 

            if (nums[currentIndex] > stepLeft) {
                stepLeft = nums[currentIndex]; 
            }
        }  

        if (currentIndex == nums.length - 1) {
            return true; 
        }

        return false; 
    }
}
profile
everything happens for a reason

0개의 댓글