0
点赞
收藏
分享

微信扫一扫

55. 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.

思路:
这道题的意思是给了一个数组,数组里面表示的是在这个位置上,最大可跳跃的位置。
思路就是使用一个贪心法,使用一个步进指针,用一个上界指针。 每次遍历的时候,不停的更新上界指针的位置(也就是当前位置+当前可以跳到的位置),知道看你能遇到结尾吗?如果成功了,就范围true,没有就返回false。

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

class Solution {
public boolean canJump(int[] nums) {
if (nums.length <= 1) {
return true;
}

int target = nums.length - 1;
int start = target - 1;
while (start >= 0) {
if (canAccess(target, start, nums)) {
if (start == 0) {
return true;
}
target = start;
start--;
} else {
start--;
}
}
return false;
}

private boolean canAccess(int target, int start, int[] nums) {
if (nums[start] >= (target - start)) {
return true;
}
return false;
}
}

class Solution {
public boolean canJump(int[] nums) {
int maxIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (maxIndex < i)
return false;

int endIndex = i + nums[i];

maxIndex = Math.max(maxIndex, endIndex);

if (maxIndex >= nums.length - 1)
return true;
}
return false;
}
}


举报

相关推荐

0 条评论