【Hot100】LeetCode—45. 跳跃游戏 II


题目


1- 思路

思路

  • 跳跃游戏——>贪心
    • 借助 curCover 记录当前覆盖范围、nextCover 记录下一次的覆盖范围
    • ① 遍历数组,如果 i 等于当前的覆盖范围,且 i 未到达终点——> 此时 res++,更新 nowCover

2- 实现

⭐45. 跳跃游戏 II——题解思路

在这里插入图片描述

class Solution {
    public int jump(int[] nums) {
        // 1.数据结构
        int res = 0;
        int nowCover = 0;
        int nextCover = 0;
        
        // 遍历 nums
        for(int i = 0 ; i < nums.length;i++){
            nextCover = Math.max(nextCover,nums[i]+i);
            if( i == nowCover){
                if(nowCover!=nums.length-1){
                    res++;
                    nowCover = nextCover;
                }
            }
        }
        return res;
    }
}

3- ACM 实现

public class jumpGame {

    public static int jump(int[] nums){
        //1. 数据结构
        int res = 0;
        int nowCover = 0;
        int nextCover = 0;

        for(int i = 0 ; i < nums.length;i++){
            nextCover = Math.max(nextCover,i+nums[i]);
            if(i==nowCover){
                if(nowCover!=nums.length-1){
                    res++;
                    nowCover = nextCover;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入数组长度n");
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0; i < n;i++){
            nums[i] = sc.nextInt();
        }
        System.out.println("最小跳为"+jump(nums));
    }
}

相关推荐

  1. LeetCode-热题10045. 跳跃游戏 II

    2024-07-16 11:22:05       34 阅读
  2. LeetCode热题10045. 跳跃游戏 II(贪心)

    2024-07-16 11:22:05       38 阅读
  3. LeetCode 面试经典15045.跳跃游戏II

    2024-07-16 11:22:05       36 阅读

最近更新

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

    2024-07-16 11:22:05       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-16 11:22:05       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-16 11:22:05       58 阅读
  4. Python语言-面向对象

    2024-07-16 11:22:05       69 阅读

热门阅读

  1. 前端面试题

    2024-07-16 11:22:05       29 阅读
  2. Linux开发:Ubuntu22.04安装Fuse3

    2024-07-16 11:22:05       27 阅读
  3. VSCODE驯服笔记(一)

    2024-07-16 11:22:05       20 阅读
  4. PostgreSQL使用(一)

    2024-07-16 11:22:05       21 阅读
  5. 扫地机器人自动回充功能

    2024-07-16 11:22:05       22 阅读
  6. 优秀代码分享

    2024-07-16 11:22:05       23 阅读
  7. 题解-运动会

    2024-07-16 11:22:05       23 阅读