[Leetcode] Jump Game II

Source: Internet
Author: User

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

Each element in the array represents your maximum jump length 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, 4]

The minimum number of jumps to reach the last index is2. (jump1step from index 0 to 1, then3steps to the last index .)

Https://oj.leetcode.com/problems/jump-game-ii/

Thought 1: I first thought about DP, and pushed forward from the back. The minimum number of steps at the current position is determined by the minimum number of steps within the range it can reach. Therefore, we need to traverse the coverage range and the complexity is slightly higher, it is not an O (n) algorithm, and the visual test times out.

Idea 2: greedy. Maintain several variables, curreach and nextreach, and update nextreach within the range of curreach until the end of curreach is overwritten.

Public class solution {public int jump (INT [] A) {if (a = NULL |. length <2) return 0; int n =. length; int step = 0; int curreach = 0; int nextreach = 0; int I; for (I = 0; I <n ;) {If (curreach> = n-1) break; while (I <= curreach) {nextreach = nextreach> (I + A [I])? Nextreach: (I + A [I]); I ++;} curreach = nextreach; Step ++;} return step;} public static void main (string [] ARGs) {system. out. println (new solution (). jump (New int [] {2, 3, 1, 1, 1, 2, 3 }));}}

Refer:

Http://www.cnblogs.com/lichen782/p/leetcode_Jump_Game_II.html

Http://blog.csdn.net/havenoidea/article/details/11853301

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.