從位置[0]出發,並記錄剩餘的可跳次數,同時跟當前的元素取最大值。
如果在最後一個索引前可跳次數為零,也代表無法跳到終點,可以提前回傳False。順利遍歷數列的話,則回傳True。
Python
class Solution: def canJump(self, nums: List[int]) -> bool: remainJump = 1 nums.pop() for num in nums: remainJump -= 1 remainJump = max(remainJump, num) if remainJump == 0: return False return TrueC#
public class Solution { public bool CanJump(int[] nums) { int remainJumps = 1; int index = 0; foreach(var num in nums) { remainJumps -= 1; remainJumps = num > remainJumps ? num: remainJumps; if (remainJumps==0 && index < nums.Length-1) { return false; } index++; } return true; } }