LeetCode 45. 跳跃游戏 II

文章目录

一、题目

  给定一个长度为 n 的 0 索引 整数数组 nums。初始位置为 nums[0]。

  每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:

  • 0 <= j <= nums[i]
  • i + j < n

  返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]。

示例 1:

输入: nums = 2,3,1,1,4
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。

从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

示例 2:

输入: nums = 2,3,0,1,4
输出: 2

提示:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 1000
  • 题目保证可以到达 nums[n-1]

  点击此处跳转题目。

二、C# 题解

  使用贪心的思想,pos 记录当前位置,ans 记录跳跃次数,achieve 记录跳一步后能到达的最远距离。

csharp 复制代码
public class Solution {
    public int Jump(int[] nums) {
        if (nums.Length == 1) return 0;
        if (nums[0] >= nums.Length - 1) return 1;
        
        int ans = 1, pos = 0, achieve = nums[0];
        while (true) {
            if (achieve >= nums.Length - 1) break;
            int tmp = achieve;
            for (int i = pos + 1; i <= tmp; i++) {
                if (i + nums[i] <= achieve) continue;
                achieve = i + nums[i];
                pos = i;
            }
            ans++;
        }

        return ans;
    }
}
  • 时间:84 ms,击败 93.33% 使用 C# 的用户
  • 内存:40.59 MB,击败 90.71% 使用 C# 的用户
相关推荐
geovindu6 小时前
python:DecisionTree
开发语言·后端·python·算法
rockey6277 小时前
AScript正式推出Template模板引擎
c#
geovindu8 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
apcipot_rain9 小时前
某游戏公司C++游开实习 机试复盘
c++·游戏
沐言Agent9 小时前
做工业上位机,这个 C# 开源框架把 PLC 通讯、流程控制和 MES 对接都备好了
c#·工业上位机
AllData公司负责人10 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康11 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长12 小时前
C++:C++11特性
开发语言·c++·算法
秋天的怀念_David12 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法