您的位置:首页 > 其它

给定一个数组,判断从开始能否走到结束,最多需要几步?

2016-03-24 18:52 459 查看
1、给定一个非负数组,数组中的元素代表从当前位置可以向后跳几步,判断能否走到数组末尾。例如:A = [2,3,1,1,4], return true;A = [3,2,1,0,4], return false.

public boolean canJump(int[] nums) {
int maxIndex = nums.length-1;
int maxJump  = nums[0];
for(int i = 0; i <= maxJump; i++){
maxJump=Math.max(maxJump,i+nums[i]);
if(maxJump>=maxIndex) return true;
}
return false;
}


2、求出从数组开始到末尾最少可以跳几次。例如:A = [2,3,1,1,4],则最少需要2步,2–>3–>4。

2.1、最直观,递归

public int jump(int[] nums) {
if(nums.length==1)return 0;
return  getLen(nums,0);
}
public int getLen(int []nums,int i){
if(i>=nums.length-1)return 0;
int val=nums[i];
int min=nums.length;
for(int j=i+1;j<=i+val;j++){
min=Math.min(getLen(nums,j),min);
}
return min+1;
}


2.2、动态规划,保存之前求过的值

public int jump(int[] nums) {
if(nums.length==1)return 0;
int dp[]=new int[nums.length];
int temp=0,len=nums.length;
for(int i=len-2;i>=0;i--){
temp=nums[i];
dp[i]=len;
temp+=i;
for(int j=i+1;j<=temp&&j<len;j++){
dp[i]=Math.min(dp[i],dp[j]);
}
dp[i]++;
}
return dp[0];


2.3、维持两个指针,一个表示当前最远可以跳到哪一步,一个表示下一步最远可以跳到哪一步。遍历原数组同时更新指针。

public int jump(int[] nums) {
if (nums.length <= 1)return 0;
int i = 0, n = nums.length, lc = 0, ln = 0, step = 1;
// lc means the longest distance can achieve by current jump
// ln means the longest distance can achieve by next jump
lc = nums[0];
ln = nums[0]; // Initialize to index 0, the start point.
for (i = 1; i < n; ++i) {
if (i > lc){ // current jump cannot get index i -->>> must jump one more time.
lc = ln;
step++;
}
if (i + nums[i] > ln)ln = i + nums[i]; // maintain the furthest distance of next jump can get
if (lc >= n - 1) return step;// current jump can achieve the last index
}
return step;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  跳步 最少步数