Leetcode45. 跳跃游戏 II

题目传送地址: https://leetcode.cn/problems/jump-game-ii/

在这里插入图片描述

代码如下:

   public static int jump(int[] nums) {
        int result = 0; //走的总步数
        for (int i = 0; i < nums.length - 1; i++) {
            int j = i + 1;
            int max = 0;
            result++;
            int nextIndex = 0; //下一个能跑最远的有潜力的点
            if (i + nums[i] >= nums.length - 1) {
                return result;
            }
            //找出下一个能跑最远的点。
            while (j <= i + nums[i]) {
                if (nums[j] + j > max) {
                    max = nums[j] + j;
                    nextIndex = j;
                }
                j++;
            }
            i = nextIndex-1;
        }
        return result;
    }

版权声明:本文为qq_40241957原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。