LeetCode Jump Game

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.