Jump Game 和 Jump Game II

Jump Game

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.

Determine if you are able to reach the last index.

A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

Jump Game II  在Jump Game 的基础上,Your goal is to reach the last index in the minimum number of jumps.

Jump Game II 思想类似于BFS,求达到目的点的最小步数,所以用BFS的思想求解即可;

见代码:JAVA

Jump Game

public boolean canJump(int[] A) {
int len = A.length;
if(len==0) return true;
int max=A[0];
int i=0;
while(i<=max) {
if(A[i] + i > max) max=A[i] + i;
if(max >= (len-1)) return true;
i++;
}
return false;
}

      

Jump Game II

public int jump(int[] A) {
int n = A.length;
if(n==0) return -1;
if(n<=1) return 0;
int j=A[0];
int i=0;
int step=1;
int max=j;
while(j<n-1) {
max=j;
if(i>max) return -1;
while(i<=j) {
if(A[i]+i>max) max=A[i]+i;
i++;
}
step++;
j=max;
}
return step;
}

代码C++

bool canJump(int A[], int n) {
int i=0,j;
int max=0;
for(i=0;i<n && i<=max;i++) {
j = A[i]+i;
if(j>=max) max = j;
if(max>=n-1) return true;
}
return false;

}

int jump(int A[], int n) {
int tmp=0;
int maxx=0;
int num=0;
for(int i=0;i<n;) {
if(tmp>=n-1) break;
while(i<=tmp) {
maxx=max(maxx,i+A[i]);
i++;
}
num++;
tmp=maxx;
}
return num;
}

posted @ 2014-06-23 22:57  purejade  阅读(124)  评论(0编辑  收藏  举报