# Leetcode 之 Jump Game

201人阅读 评论(0)

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

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：51071次
• 积分：1260
• 等级：
• 排名：千里之外
• 原创：75篇
• 转载：12篇
• 译文：0篇
• 评论：5条
评论排行
最新评论