您的位置:首页 > 其它

leetcode习题解答:45. Jump Game II

2017-12-21 23:42 393 查看
难度: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.
思路:
最开始看到这个题的时候想用DP,但是想不出来怎么用。。。

之后观察到jump这个动作可以用连线来表示,把数组中的序号变成一个个节点,这就变成了一个求最短路径的图论问题了有木有。

然而。。不行。正确性没问题,超时了。

可见这个题目对算法性能有要求。

在网上搜索后,知道了这个题目该如何在O(n)时间内求解。

leetcode讨论区的dalao的代码:

public int jump(int[] A) {
int sc = 0;
int e = 0;
int max = 0;
for(int i=0; i<A.length-1; i++) {
max = Math.max(max, i+A[i]);
if( i == e ) {
sc++;
e = max;
}
}
return sc;
}

很短,但是什么意思啊。
其实其本质是寻找一个区间内的节点能跳到的最远距离,而e就是记录着这一跳能跳到最远的地方,我们知道从上一个区间跳一次最多只能跳到e,所以无论如何这一跳也终结了,不可能再远了,这时sc++,sc变量就是记录跳数的。

从上个区间选出来的e到这个区间选出来的e,又是一个新的寻找的区间,在这个区间中寻找能跳到最远的序号。

当e超过数组最大序号时,说明可以结束了,上面的代码没有对e做什么检验,令i在处理倒数第二个数组项目后停下。不处理最后的一项?

因为最后一项的值没有意义,但是如果之前的e是数组最后一项的序号,也就是说上一个区间最多能跳到最后,那么会导致跳数加多一个。

代码:

class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() == 1) return 0;
int jumpstep = -1;
int max = 0;
int maxdis = 0;
for(int i = 0; i < nums.size();i++){
if(nums[i]+i > max) max = nums[i]+i;
if (maxdis == i){
jumpstep++;
maxdis = max;
if (max >= nums.size()-1) return (jumpstep+1); //下一个区间包括了最后一项,直接返回当前跳数+1
}
}
return jumpstep;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: