LeetCode Jump Game
LeetCode-solving: Jump Game
Original question
Each value in the array indicates that you can skip a few steps forward at the current position to determine whether the given array exists.
Note:
All numbers are positive skip steps, which can be smaller than the current value.
Example:
Input: nums = [2, 3, 1, 1, 4]
Output: True
Input: nums = [3, 2, 1, 0, 4]
Output: False
Solutions
First, think about when the jump will not be completed. The longest distance before the current position (including the current position) will be the current position, and it will not be reached yet; in what circumstances can we ensure that we can jump to the end point, as long as the current maximum distance exceeds the end point. As long as the current position does not exceed the maximum distance that can be jumped to, you can constantly refresh the maximum distance to continue.
AC Source Code
class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ if not nums: return False length = len(nums) index = 0 longest = nums[0] while index <= longest: if longest >= length - 1: return True longest = max(longest, index + nums[index]) index += 1 return Falseif __name__ == "__main__": assert Solution().canJump([2, 3, 1, 1, 4]) == True assert Solution().canJump([3, 2, 1, 0, 4]) == False