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;}

运行结果
这里写图片描述
这里写图片描述

原创粉丝点击