LeetCode No.45 Jump Game II

来源:互联网 发布:淘宝网宝宝床 编辑:程序博客网 时间:2024/06/01 09:48

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.

====================================================================================
题目链接:https://leetcode.com/problems/jump-game-ii/

题目大意:给定一组非负整数组,每个节点的元素表示该节点能跳到最远距离,求跳到最后一个节点至少需要多少步。(题目保证可达)

思路:用堆来实现,节点Node有两个元素index和step,分别表示该点下标和到达该点的最小步数。排序方式为最小步数的放队头(保证程序的正确性),相同步数的将下标最小的放队头。

注意点:用一个bool数组记录该节点是否被访问过, 防止多次访问。

附上代码:

struct Node {    int index , step  ;    Node (){}    Node ( int i , int s )// 下标、到达改点步数    {        index = i ; step = s ;     }    bool operator < ( const Node& a ) const    {        if ( a.step == step )//相同步数的将下标最小的放队头            return a.index > index ;        return a.step < step ;//最小步数的放队头    }};class Solution {public:    int jump(vector<int>& nums) {        int n = nums.size() ;        if ( n <= 1 )            return 0 ;        priority_queue <Node> q ;        q.push ( Node ( 0 , 0 ) ) ;        vector <bool> visit ( n , false ) ;        visit[0] = true ;        while ( ! q.empty() )        {            Node temp = q.top() ;            q.pop () ;            for ( int i = temp.index + 1 ; i <= temp.index + nums[temp.index] ; i ++ )            {                if ( i >= n - 1 )                    return temp.step + 1 ;                if ( ! visit[i] )                {                    visit[i] = true ;                    q.push ( Node ( i , temp.step + 1 ) ) ;                }            }        }        return 0 ;    }};

可是,通过是通过了,只打败了2%的程序。这样的时间复杂度是远远不够的。无奈之下,还是去瞻仰一下大神们的做法。

具体思路如下:

1、ans: 目前为止的jump数
2、curMax: 从nums[0]进行ans次jump之后达到的最大范围
3、nextMax: 从0~i这i+1个nums元素中能达到的最大范围
4、当curMax < i,说明ans次jump已经不足以覆盖当前第i个元素,因此需要增加一次jump,使之达到记录的nextMax。

贴上代码:

class Solution {public:    int jump(vector<int>& nums) {        int n = nums.size() ;        int curMax = 0 , ans = 0 , nextMax = 0 ;        for ( int i = 0 ; i < n ; i ++ )        {            if ( curMax < i )            {                ans ++ ;                curMax = nextMax ;            }            nextMax = max ( nextMax , nums[i] + i ) ;        }        return ans ;    }};


0 0
原创粉丝点击