iT邦幫忙

0

解LeetCode的學習筆記Day55_Jump Game

LFI 2025-11-15 23:31:24156 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第五十五天

第五十五題題目: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.

給定一個整數數組nums,初始位置在索引0,數組中每個元素代表你在該位置的最大跳躍距離,如果可以到達最後一個索引回傳true,否則回傳false

解題思路

這題跟45題是同樣的概念,一樣定義farthest是每一跳可以到達的最遠距離,cur_end表示當前跳躍的長度,當cur_end == i時,表示到達最遠可達距離,最後只要判斷cur_end是否有超過最後一個索引處就代表能不能抵達終點

程式碼

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

執行過程可看day45的文章


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言