贪心算法-跳跃游戏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]。
输入:数组
输出:整型
思路:
- 从右往左,先让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)
- 使用正向遍历,记录可以到达的最远位置
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)的理解
- 对于不需要遍历到最后一个元素的理解