Jump Game

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

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.

给定一个非负整数数组,您最初定位在数组的第一个索引处。

数组中的每个元素表示该位置的最大跳转长度。

确定您是否能够到达最后一个索引。

2,题目思路

对于这道题,要求的是数组中的每个值代表可以跳转的最大步数,问是否可以跳转到最后一个位置。

在做这道题时,个人最初的想法是使用动态规划,毕竟题目的形式和要求都和动态规划的问题非常类似。

不过实际没有必要。

对于一个数组num,假设它的长度为n,那么,我们需要获得的是前n-1个数字所能达到的最大的范围。

在计算这个最大范围的同时,我们也让i依次遍历,看i能否到达最后一个index

注:只计算最大范围是不行的,比如对于num = [0,1,2],计算最大距离是1,但是并不能到达最后一个元素的位置,因为第一步就走不出去。

3,代码实现

int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution {
public:
    bool canJump(vector<int>& nums) {
        if(nums.size() == 0)
            return true;
        
        int n = nums.size();
        int canReachRange = 0;
        int i = 0;
        
        //i一步步往前走
        //在判断是否走到n-1位置的同时,也在计算最大可到达的范围
        //如果判断条件为真,最后break时,i == n
        for(;i<n && i<=canReachRange;i++)
            canReachRange = max(canReachRange, i + nums[i]);	

        return i == n;
    }
};


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值