您的位置:首页 > 其它

Leetcode 55. Jump Game & 45. Jump Game II

2016-03-29 07:18 597 查看


55. Jump Game

Total Accepted: 73675 Total
Submissions: 262004 Difficulty: Medium

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
.

一开始二维DP→一维DP从左到右一遍。TLE了;然后改进了一下,从后往前,跳过不能到达的case判断,递归,TLE;然后倒序加一维DP,TLE。。

怒搜网上攻略。。原来DP是O(n^2),所以超时。

比较好的解法是用一个变量保存目前能走的最远距离。然后从开始扫一遍,如果当前i大于这个最远距离,说明无法到达i位置,则返回false。否则不断更新最远距离并判断该值是否大于等于数组长度减一。

public class Solution { //4ms
public boolean canJump(int[] nums) {
if (nums == null || nums.length <=1 ) return true;
int len = nums.length;
int far = nums[0];
for (int i=0; i<len; i++){
if(i>far) return false;
far = Math.max(far, i+nums[i]);
if(far>=len-1) return true;
}
return true;
}
}



45. Jump Game II

Total Accepted: 60959 Total
Submissions: 242182 Difficulty: Hard

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.)
Note:

You can assume that you can always reach the last index.

这题一开始想了半天,总想着如果走了最大的路线,又不能到最后,那又得折回去,这多麻烦,还得记个max list。

后来看了别人解答发现( http://www.shuatiblog.com/blog/2014/05/14/Jump-Game-II/ ),同样的思路,有一个farthest变量,并且有start end俩变量。每次先判断end是否大于等于数组长度-1,是则返回次数,否则说明没到末尾则step++。然后从start到end,更新farthest。point就在于不用担心不会到达最后,因为题目说了可以到达,所以每次走最大的,一定能到达。更新完毕之后,下次的开始是这次end+1,下次的end是目前的farthest。

内层的start,end更新farthest,其实就相当于DP。从0~10,最远距离是到15,可能4能到15,8也能到15。不管哪个点,总step都是加1,所以应该是DP,而不是说扫到4发现jump值为11最大,就选4。GREEDY和DP的区别不就在这。

public class Solution { //3ms
public int jump(int[] A) {
if (A == null || A.length <= 1) {
return 0;
}
int len = A.length;
int jumps = 0;
int left = 0;
int right = 0;

while (right < len) {
int reachable = right;
jumps++;
for (int i = left; i <= right; i++) {
reachable = Math.max(reachable, i + A[i]);
}
if (reachable == right) {
// unable to jump forward
return -1;
}
if (reachable >= len - 1) {
return jumps;
} else {
left = right + 1;
right = reachable;
}
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: