LeetCode No.55 Jump Game

来源:互联网 发布:上海华云数据 知乎 编辑:程序博客网 时间:2024/06/06 01:46

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.

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

题目大意:给定一个非负整数的数组,下标i对应的nums[i]表示在该下标可以最远跳到下标i+nums[i],求从下标0能不能跳到下标n-1。

思路:题目总得来说还是比较通俗易懂的,求解能不能到达,就是一个可达性问题,通常这种问题我们都是用深搜(DFS),但是这道题有点不太一样,就是每个节点的值已经固定了,我们可以用优先队列priority_queue来优化我们的算法。

注意点:首先要判断有没有某个节点可以到达最后一个节点,如果都不能就可以直接返回false

附上代码:

class Solution {public:    bool canJump(vector<int>& nums) {        int n = nums.size() ;        if ( n <= 1 )            return true ;        bool isValid = false ;        for ( int i = 0 ; i < n - 1 ; i ++ )        {            if ( nums[i] + i >= n - 1 )            {                isValid = true ;                break ;            }        }        if ( ! isValid )            return false ;        priority_queue <int> q ;        vector <bool> visit ( n , false ) ;        visit[0] = true ;        q.push ( 0 ) ;        while ( ! q.empty() )        {            int node = q.top() ;            q.pop() ;            if ( nums[node] + node >= n - 1 )                return true ;            for ( int i = node + 1 ; i <= node + nums[node] ; i ++ )            {                if ( ! visit[i] )                {                    q.push ( i ) ;                    visit[i] = true ;                }            }             }        return false ;    }};


0 0
原创粉丝点击