您的位置:首页 > 其它

[leetcode]Jump Game

2016-01-18 17:48 253 查看
题目描述如下:

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.

类似跳格子,判断能否到达最后一个。

明显的动归题,受到昨天Coin Change的影响Coin Change,第一版代码如下:

public class Solution {
public boolean canJump(int[] nums) {
boolean judgeArray[] = new boolean[nums.length];
judgeArray[0] = true;
int i, j;
for(i = 0; i < nums.length; i++){
if(judgeArray[i]){
int limit = i + nums[i] < nums.length - 1 ?
i + nums[i] : nums.length - 1;
for(j = i + 1; j <= limit; j ++)
judgeArray[j] = true;
}
}
return judgeArray[nums.length - 1];
}
}


在最后一个大数据的测试下TLE了。

之后对此做了各种优化,判断在一个点的时候最远能到达的位置有没有超过最后一个元素。个人感觉思路是没有错的,然而各种TLE和RE。

无奈最后参考了别人的代码。

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


很巧妙的是记录当前能到达的最远距离与点的位置的比较。我之前所标记的是点的位置因此逻辑变得很复杂。

总归是自己对动归运用的不熟练,还要多练习。

题目链接:https://leetcode.com/problems/jump-game/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: