力扣55. 跳跃游戏

Problem: 55. 跳跃游戏

题目描述

在这里插入图片描述

思路

将题目稍作转化:验证最远走到的距离是否超出组数

1.获取数组nums的长度n,定义int变量farthest初始化为0;
2.从0~n-1循环每次更新farthes的长度farthest = max(farthest, i + nums[i]);
3.若中途遇到0则跳不出去需要进行判断(若farthest <= i,则直接返回false)
4.最终判断farthest是否大于n - 1;

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为数组nums的大小

空间复杂度:

O ( 1 ) O(1) O(1)

Code

class Solution {
public:
    /**
     * Dynamic programming
     * 
     * @param nums Given array
     * @return bool
     */
    bool canJump(vector<int>& nums) {
        int n = nums.size();
        int farthest = 0;
        for (int i = 0; i < n - 1; ++i) {
            farthest = max(farthest, i + nums[i]);
            //Meet to 0
            if (farthest <= i) {
                return false;
            }
        }
        return farthest >= n - 1;
    }
};

相关推荐

  1. 55.跳跃游戏、45.跳跃游戏

    2024-04-12 03:02:02       38 阅读
  2. 经典面试题】55. 跳跃游戏

    2024-04-12 03:02:02       45 阅读
  3. 】45.跳跃游戏

    2024-04-12 03:02:02       30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-12 03:02:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-12 03:02:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-12 03:02:02       82 阅读
  4. Python语言-面向对象

    2024-04-12 03:02:02       91 阅读

热门阅读

  1. 关于搭建elk日志平台

    2024-04-12 03:02:02       39 阅读
  2. 设计模式:命令模式示例

    2024-04-12 03:02:02       37 阅读
  3. [RK3399 Linux] 移植U-Boot 2023.04 & Linux 6.3

    2024-04-12 03:02:02       40 阅读
  4. 《1w实盘and大盘基金预测 day19》

    2024-04-12 03:02:02       38 阅读
  5. React中State管理的4 个关键解决方案

    2024-04-12 03:02:02       39 阅读
  6. vue2-vue3面试

    2024-04-12 03:02:02       29 阅读
  7. Animation动画控制脚本

    2024-04-12 03:02:02       38 阅读