您的位置:首页 > 其它

[LeetCode]Jump Game

2016-10-24 16:54 274 查看
Question

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.

For example:

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

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

本题难度。有2种算法分别是:双指针法和贪心法。

1、双指针法

【复杂度】

时间 O(N) 空间 O(1)

【思路】

Jump Game II的双指针法一样。不过题目Jump Game II有个前提是它一定能跳到最后一个元素;而这里是不一定能跳到最后。不能跳到最后只有一种可能:原地踏步。所以我用11-12行来判断。

【代码】

public class Solution {
public boolean canJump(int[] nums) {
//require
int size=nums.length;
int high=0,low=0,preHigh=0;
while(high<size-1){
preHigh=high;
for(int i=low;i<=preHigh;i++)
high=Math.max(high,nums[i]+i);
low=preHigh+1;
if(high==preHigh)
return false;
}
//ensure
return true;
}
}


2、贪心法

【复杂度】

时间 O(N) 空间 O(1)

【思路】

如果只是判断能否跳到终点,我们只要在遍历数组的过程中,更新每个点能跳到最远的范围就行了,如果最后这个范围大于等于终点,就是可以跳到。

【代码】

public class Solution {
public boolean canJump(int[] nums) {
int max = 0, i = 0;
for(i = 0; i <= max && i < nums.length; i++){
max = Math.max(max, nums[i] + i);
}
return i == nums.length;
}
}


参考

Jump Game I
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode