Leetcode notes: Jump Game II

Source: Internet
Author: User

I. Title Description

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 ArrayA = [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 3 steps to the last index.)

Two. Topic analysis

The main idea of the problem is that given an array, each element represents the distance that can be jumped from that position, asking at least how many times to jump from the first position to the last position.

Unlike jump game, the jump game asks if the array jumps to the last grid, which requires the number of hops to be calculated. The solution is still greedy, just set an array to record the path of the jump.

Three. Sample code

Class Solution { Public:int  Jump(intA[],intN) {intresult =0;//Current number of hops        intLast =0;//The maximum distance the previous hop can reach        intCurr =0;//The maximum distance the current hop can reach         for(inti =0; I < n; ++i) {//Cannot forward skip direct return            if(i > Curr)return-1;//need to make the next jump, update last and the currently executed hop count result            if(i > Last)                {last = Curr;            ++result; }//Update the furthest distance currently available for jumpingCurr = Max (Curr, I+a[i]); }returnResult }};

Four. Summary

Similar problem-solving ideas and BFS, the latter can be verified verification.

Leetcode notes: 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.