Leetcode 45. Jump Game II

Source: Internet
Author: User

Given an array of non-negative integers, you is initially positioned at the first index of the array.

Each element of the array represents your maximum jump length is at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A =[2,3,1,1,4]

The minimum number of jumps to reach the last index is 2 . (Jump 1 Step from index 0 to 1 and then steps to the last 3 index.)

Note:
You can assume so can always reach the last index.

Problem Solving Ideas:

Check where the nth jump is farthest, if the nth step of Maxreach >= n-1, then the answer is N. The first jump of the Maxreach is Numns[0] (the legend is equal to 5), the second jump of the Maxreach is head1 to MAX1 decision. The Maxreach of the third jump is determined by head2 and MAX2. And so on

1 classsolution (object):2     defJump (Self, nums):3         """4 : Type Nums:list[int]5 : Rtype:int6         """7n =Len (nums)8Njumps = Maxreach = head =09         Ten          whileMaxreach < n-1: OneNjumps + = 1 ACurmax =Maxreach -              forIinchRange (Head, maxreach+1): -Curmax = Max (Curmax, i+Nums[i]) theHead = Maxreach + 1 -Maxreach =Curmax -          -         returnNjumps

Leetcode 45. Jump Game II

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.