leetcode45:跳跃游戏II
-
题目:
-
给定一个非负整数数组
nums,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
-
-
思路:贪心算法
-
代码如下:
class Solution {
public int jump(int[] nums) {
int res = 0;
//下一步覆盖最远距离
int nextDistance = 0;
//当前覆盖最远距离
int curDistance = 0;
int n = nums.length;
//提前对当前可以走的最远距离+1
//当当前可以走的最远距离超过nums的长度-2时,说明已经符合要求,直接返回结果即可
for(int i = 0; i <= curDistance && curDistance < n - 1; i++){
//从上一次走的最远最远距离开始,记录下一次走的最远距离
nextDistance = Math.max(nextDistance,i+nums[i]);
if(i == curDistance){
//说明已经到达当前走最远距离,将下次走的最远距离赋值给当前走的最远距离,跳跃数+1
curDistance = nextDistance;
res++;
}
}
return res;
}
}
本文解析了如何使用贪心算法解决LeetCode题目45,涉及给定数组的跳跃游戏,通过计算每次跳跃的最大距离来判断能否到达数组末尾。代码展示了如何利用当前覆盖距离和最大跳跃距离来逐步推进解决方案。
343

被折叠的 条评论
为什么被折叠?



