# Leetcode 之 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.

    public boolean canJump(int[] nums) {
int len = nums.length;
boolean can[] = new boolean[len];

can[0] = true;
for(int i = 0;i < len;i++){
if(can[i] == true){
for(int j = 0;j <= nums[i] && (i + j < len);j++){
can[j + i] = true;
}
}
}

return can[len - 1];
}

public boolean canJump(int[] nums){
int len = nums.length;
if(len == 0 || len == 1)    return true;
int maxStep = nums[0];

for(int i = 1;i < len;i++){
if(maxStep == 0)    return false;
maxStep--;
if(maxStep < nums[i])   maxStep = nums[i];
if(maxStep + i >= len - 1)  return true;
}
return false;
}

71 / 71 test cases passed.
Status: Accepted
Runtime: 364 ms

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

II是还要求出最小跳数，也就是要记录每一步是在哪儿跳的。还是用贪心。设置两个游标，一个记录当前能够到的最远位置curr，一个记录跳的停留的位置last。

public int jump(int[] nums){
int last = 0;
int curr = 0;
int times = 0;

for(int i = 0;i < nums.length;i++){
if(i > curr)    return -1;
if(i > last){
last = curr;
times++;
}
curr = Math.max(curr, i + nums[i]);
}
return times;
}


91 / 91 test cases passed.
Status: Accepted
Runtime: 400 ms

• 本文已收录于以下专栏：

举报原因： 您举报文章：Leetcode 之 Jump Game 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)