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.
public int jump(int[] A) {
if(A==null || A.length==0)
return 0;
int lastReach = 0;
int reach = 0;
int step = 0;
for(int i=0;i<=reach&&i<A.length;i++)
{
if(i>lastReach)
{
step++;
lastReach = reach;
}
reach = Math.max(reach,A[i]+i);
}
if(reach<A.length-1)
return 0;
return step;
}
Using DP, Code from Jump Game II
Read full article from Jump Game II
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:Using Greedy Algorithm: O(n)
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, then 3 steps to the last index.)
int jump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n == 1)
return 0;
int jumps = 0;
int currMax = 0;
int i = 0;
while (i < n)
{
currMax = A[i] + i;
if (A[i] > 0)
++jumps;
else
return 0;
if (currMax >= n - 1)
return jumps;
int tmpMax = 0;
for (int j = i + 1; j <= currMax; ++j)
{
if (A[j] + j >= tmpMax)
{
tmpMax = A[j] + j;
i = j;
}
}
}
return jumps;
}
Code from http://blog.csdn.net/linhuanmars/article/details/21356187public int jump(int[] A) {
if(A==null || A.length==0)
return 0;
int lastReach = 0;
int reach = 0;
int step = 0;
for(int i=0;i<=reach&&i<A.length;i++)
{
if(i>lastReach)
{
step++;
lastReach = reach;
}
reach = Math.max(reach,A[i]+i);
}
if(reach<A.length-1)
return 0;
return step;
}
Using DP, Code from Jump Game II
int jump(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if(n <= 1) return 0; const int noWay = n + 1; int *jumps = new int[n]; jumps[n-1] = 0; for(int i = n - 2; i >= 0; -- i) { int lenJump = A[i]; int minJumps = noWay; for(int j = i + 1; j <= i + lenJump && j < n; ++ j) { if(jumps[j] + 1 < minJumps) minJumps = jumps[j] + 1; } jumps[i] = minJumps; } return jumps[0]; }Also refer to http://www.darrensunny.me/leetcode-jump-game-ii/
Read full article from Jump Game II
No comments:
Post a Comment