코딩테스트/Python

[LeetCode] 55. Jump Game

swwho 2023. 12. 4. 14:44
728x90
반응형

🔗 Problem Link

 

Jump Game - LeetCode

Can you solve this real interview question? Jump Game - 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

leetcode.com


❔Thinking

  • 현재의 nums값은 갈 수 있는 최대 칸의 개수를 의미한다.
  • nums의 길이가 10000까지이고, nums의 값이 100000까지 이므로, 모든 경로를 탐색할 수 없다.

💻Solution

def canJump(self, nums: List[int]) -> bool:
    reachable = nums[0]
    for i in range(len(nums)):
        if reachable < i:
            return False
        else:
            reachable = max(reachable, i+nums[i])
    return True

🗝️keypoint

  1. 값을 하나씩 확인하면서, 현재보다 더 멀리 갈 수 있는 경우를 찾아 저장한다.
  2. 현재의 값보다 작은 값들은, 결국 더 멀리 갈 수 없음을 의미한다.