Leetcode greedy Jump Game II, leetcodejump

Source: Internet
Author: User

Leetcode greedy Jump Game II, leetcodejump
Jump Game II Total Accepted: 16242 Total Submissions: 65802My Submissions

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,1,4]

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


Question:
To an array containing non-negative integers, each number represents the maximum Jump Distance. The initial position is
Returns the minimum number of steps required to jump to the last position of the array.
Idea: greedy
Define two variables: start and end,
Start indicates the starting point of the array element that has not been scanned,
End indicates the current location that can be reached,
Scan the array, constantly expand the end, and update the start. Every such process is a step.

Complexity: O (n)


Int jump (int A [], int n) {if (n <= 1) return 0; int start = 0, end = 0, count = 0; while (1) {count ++; int _ max = end; // _ max indicates the farthest position in the [start, end] range for (int I = start, I <= end; ++ I) {_ max = max (_ max, I + A [I]); if (_ max> = n-1) {return count ;}} start = end; end = _ max ;}}





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.