LeetCode - Jump Game II

来源:互联网 发布:grub修复系统引导linux 编辑:程序博客网 时间:2024/06/15 13:38

https://leetcode.com/problems/jump-game-ii/

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


这道题是Jump Game的进化版,求的不是能不能到达,而是到达最后一个需要的最小步数。

本来我想用DP,即每到一格,则更新它所达范围内的步数。但是这样的话时间复杂度是O(n^2).

于是看了别人的解法,发现只要有两个变量,end和step,end是用当前step能够到达的最远值,furthest是扫描过的格子中能够到达的最远值,如果end<i<furthest,就step++,然后更新end至新的furthest值。

代码如下:

public class Solution {    public int jump(int[] A) {        int furthest = 0;        int steps = 0;        int end = 0;        int i = 0;        while(i<A.length && i<=furthest){            int dest = i+A[i];            if(i>end){                steps++;                end = furthest;            }            if(dest>furthest) furthest = dest;            if(i==(A.length-1)) return steps;            if(furthest>=(A.length-1)) return steps+1;            i++;        }        return -1;    }}

注意,下面代码块中两个if的顺序不能反了:
if(i>end){    steps++;    end = furthest;}if(dest>furthest) furthest = dest;

因为当i>end时,已经进入下一个step的范围,而这时的end需要更新为上一个step所能到达的furthest,所以应该是在furthest更新为当前i所能到达范围之前的范围。

感觉我的代码还是挺难懂的,http://fisherlei.blogspot.com/2012/12/leetcode-jump-ii.html , 这里的代码好懂一些,主要就是多了一个for循环,增加易读性。但是他的算法的问题是,如果最后不能到达的话,就会陷入死循环。

增加C++代码:

class Solution {public:    int jump(vector<int>& nums) {        int furthest=0;        int step = 0;        int end = 0;        int i=0;        while(i<=furthest && i<nums.size()){            if(i>end){                step++;                end = furthest;            }            int goal = i+nums[i];            if(goal > furthest) furthest = goal;            if(i==(nums.size()-1)) return step;            if(furthest>=(nums.size()-1)) return step+1;            i++;        }        return -1;    }};


0 0
原创粉丝点击