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 =
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.)
public class Solution {
public int jump(int[] A) {
if(A==null || A.length==0) {
return -1;
}
if(A.length==1) {
return 0;
}
int stepLeft = 1;
int step[] = new int[A.length+1];
int maxCover = 0;
for(int i=0;i<A.length+1;i++) {
step[i] = i-1;
}
for(int i=0;i<A.length;i++) {
stepLeft = A[i];
int max=stepLeft + i;
for(int j=maxCover+1;j<=max && j<A.length;j++) {
step[j+1] = Math.min(step[j+1], 1 + step[i+1]);
}
if(max>maxCover) {
maxCover = max;
}
}
return step[A.length];
}
}
public class Solution {
public int jump(int[] A) {
if(A==null || A.length<=1) {
return 0;
}
int cover = A[0];
int lastCover = 0;
int steps = 1;
while(cover<A.length-1) {
int nextCover = cover;
for(int i=lastCover+1;i<=cover;i++) {
nextCover = Math.max(nextCover, i+A[i]);
}
if(nextCover==cover) return -1;
else steps ++;
lastCover = cover;
cover = nextCover;
}
return steps;
}
}
public class Solution {
public int jump(int[] A) {
if(A==null || A.length<=1) {
return 0;
}
int cover = A[0];
int lastCover = 0;
int steps = 1;
while(cover<A.length-1) {
int nextCover = cover;
for(int i=lastCover+1;i<=cover;i++) {
nextCover = Math.max(nextCover, i+A[i]);
}
if(nextCover==cover) return -1;
else steps ++;
lastCover = cover;
cover = nextCover;
}
return steps;
}
}
没有评论:
发表评论