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.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
解题思路:
这道理我好像在之前的题中做过...
大概思路就是先将第一个点作为点A,第一个点能够跳到的最远的点为点B,如果B已超过终点,说明成功。
然后在A到B之间(包括),寻找这些点里面能够跳到的最远的点C,如果C小于等于B,说明在A到B之间最远只能跳到B,所以没法跳过终点,说明失败。
反之,令A = B,B = C,继续上一步的操作,直到B大于等于之后的点的坐标或者C<=B。
public class Solution {
public boolean canJump(int[] nums) {
if(nums.length < 2 || nums == null)
return true;
int nextindex = nums[0];
int firstindex = 1;
while(nextindex < nums.length-1)
{
if(firstindex > nextindex)
return false;
int maxn = 0;
while(firstindex <= nextindex)
{
maxn = Math.max(maxn, nums[firstindex] + firstindex);
firstindex++;
}
nextindex = maxn;
}
return true;
}
}