题目来源
https://leetcode.com/problems/jump-game/description/
题目描述
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.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
给出一个非负整数构成的数组. 开始时假设你正处于数组的开始处(即0号下标处), 当前下标对应的数组值表示了你在这个位置上能往后跳的最大步数.
如果你能够跳到数组最后, 则返回true, 反之返回false.
解题思路
这题大致比较简单. 我们可以遍历一遍数组, 在这个过程中维护一个初始值为 1 的变量energy, 表示在当前遍历到的第 i 个位置上能往后走的最大步数. 当到达数组最后或energy变为0时结束遍历.
最后只需要检查 i==nums.size()
成立与否即可,
代码实现
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
bool canJump(vector<int>& nums) {
int energy = 1;
int count;
for (count = 0; count < nums.size()&&energy; count++) {
energy = max(energy - 1, nums[count]);
}
return count==nums.size();
}
};