欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 贪心算法-跳跃游戏II

贪心算法-跳跃游戏II

2025/5/6 8:02:55 来源:https://blog.csdn.net/qq_46103963/article/details/147546153  浏览:    关键词:贪心算法-跳跃游戏II

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. 从右往左,先让position等于最右边,然后遍历数组,找到最小能到达的下标,然后更新position,直到position==0
class Solution {public int jump(int[] nums) {int position = nums.length - 1;int step = 0;while(position != 0){for(int i = 0; i < position; i++){if(i + nums[i] >= position){position = i;step++;break;}}}return step;}}
}

方法一虽然可以实现,但是时间复杂度高O(n2)

  1. 使用正向遍历,记录可以到达的最远位置
class Solution {public int jump(int[] nums) {int len = nums.length;int end = 0;int maxPosition = 0;int step = 0;for(int i = 0; i < len - 1; i++){maxPosition = Math.max(maxPosition, i + nums[i]);if(i == end){end = maxPosition;step++;}}return step;}
}

注意两点

  • 对于if(end == i)的理解
  • 对于不需要遍历到最后一个元素的理解

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词