55.Jump Game

问题描述
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值