Jump Game Leetcode #55 题解[C++]

22 篇文章 0 订阅
18 篇文章 0 订阅

题目来源


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

ac

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值