55.Jump Game
来源:互联网 发布:如何变文艺知乎 编辑:程序博客网 时间:2024/06/11 12:33
问题描述
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.
解题思路
该问题给出一组整型的向量,要求判断从向量的头部开始,该位置的数字代表从该位置可以前进的步数,要求判断能否到达向量尾部。我们可以这样思考,题目只要求判断能否到达尾部,并没有要求写出路径,所以我们从头开始判断可以到达的最大的位置,用一个中间变量记录此位置可以到达的最大位置,遍历完所有可以到达的位置,最后判断最长路径是否大于或等于最后的位置的长度即可。
代码展示
#include<iostream>#include<math.h> #include<vector>using namespace std;class Solution {public: bool canJump(vector<int>& nums) { int reach=0; int size = nums.size(); int i=0; while(i<size && i<=reach){ reach=max(reach,i+nums[i]); i++; } return reach>=size-1; }};int main(){ int n,a; vector<int> nums; cout<<"请输入向量长度:"; cin>>n; while(n--){ cin>>a; nums.push_back(a); } Solution solution; bool result = solution.canJump(nums); if(result == 1) cout<<"true"<<endl; else cout<<"false"<<endl; return 0;}
运行结果
阅读全文
0 0
- 55. Jump Game && 45. Jump Game II
- 55. Jump Game. 45. Jump Game II
- [LeetCode]55.Jump Game
- LeetCode 55.Jump Game
- LeetCode --- 55. Jump Game
- [Leetcode] 55. Jump Game
- [leetcode] 55.Jump Game
- 55. Jump Game
- 55. Jump Game
- [leetcode] 55.Jump Game
- *LeetCode 55. Jump Game
- LeetCode 55. Jump Game
- [leetcode] 55. Jump Game
- 55. Jump Game
- leetcode 55. Jump Game
- 55. Jump Game LeetCode
- 【LeetCode】55. Jump Game
- 55. Jump Game
- 使用Flexible实现手淘H5页面的终端适配
- Softmax回归
- 电路试验
- 使用C3P0时,数据库链接死锁的解决
- LeetCode 解题
- 55.Jump Game
- three.js 画一个旋转的立方体
- python 手记9 〖笨方法学python习题30〗
- 教程篇(5.4) NSE4 08. 显式代理 ❀ 飞塔 (Fortinet) 网络安全专家
- java 自我知识总结(十八)final finalize finally
- 如何写一个RPC框架(六):负载均衡
- C#基础之静态类
- $.ajax()方法详解
- SpringBoot与Thymeleaf整合