今天是紀錄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的文章