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
. (Jump1
Step from index 0 to 1, then3
Steps 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 ;}}