Leetcode 55. Jump Game

本文介绍了一个经典的编程问题——Jump Game。任务是从数组的第一个元素出发,根据每个元素的数值决定可以跳跃的最大长度,判断是否能够到达数组的末尾。文章提供了一种有效的解决方案,并附带了详细的实现代码。

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


题目链接:https://leetcode.com/problems/jump-game/description/

题目大意:给定一个数组,每个数字代表当前可向后走的最大步数。从第一个数字开始,求是否能走到最后一个数字位置,若能,返回true,否则返回false。

解题思路:纪录当前能走的最大步数,即从前一步的最大步数减一和当前下标对应步数中选择最大的一个,如果最大步数非零,向前走一步,直到走到最后一个数字。

代码如下:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int n = nums.size();
        int i = 0;
        int cur = nums[0];
        while(i < n - 1){
            cur = max(cur - 1,nums[i]);
            if(cur >= 1)
                i ++;
            else if(cur == 0 && i <= n-2){
                return false;
            }
        }
        return true;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值