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
- Leetcode NO.55 Jump Game
- LeetCode No.55 Jump Game
- 【LeetCode】No.55 Jump Game
- LeetCode 55: Jump Game
- [leetcode 55] Jump Game
- LeetCode(55) Jump Game
- [LeetCode 55]Jump Game
- leetcode || 55、Jump Game
- LeetCode-55-Jump Game
- leetcode-55 Jump Game
- Jump Game - LeetCode 55
- 【Leetcode】Jump Game #55
- Leetcode #55 Jump Game
- 【LeetCode】55:Jump Game
- LeetCode(55) Jump Game
- Leetcode#55||Jump Game
- (leetcode #55)Jump Game
- Leetcode 55 - Jump Game
- gridview显示上方图片下方文字
- php进阶篇
- meta viewport的使用
- ext4 学习笔记(四) [Ext.windowGroup](白鹤翔第一季)
- apache二级域名的绑定
- LeetCode No.55 Jump Game
- 并查集-hdu1232
- 主界面(关于信号检测)
- 深入理解C++动态绑定和静态绑定
- 利用JavaScript实现天气菜单栏在网页边角处展现和隐藏的效果
- 傅里叶和离散余弦变换
- 14、Spring MVC 之 multipart (file upload) support
- 桥接模式和适配器模式的区别
- LeetCode 292. Nim Game