题目内容:
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解赏析:
见最热题解
上来先用DP,没想到最后一个用例搞的很暴力,超时了,然后考虑贪心,
这里肯定贪的是最长距离,我自己写的笨了,还用了回溯,每轮去找本轮
最大的距离,写的不简洁
自己代码:
public class JumpGame { public int jump(int[] nums) { //异常场景判定 if (nums.length == 1){ return 0; } Stack<Node> stack = new Stack<Node>(); stack.add(new Node(0,0)); while (stack.size() > 0) { Node node = stack.pop(); int currentCount = node.count + 1; //是否已经达标 if (node.currentIndex + nums[node.currentIndex] >= nums.length -1){ return currentCount; } //不停迭代,贪向前扩最大的点 int current = node.currentIndex; int end = current + nums[current]; int max = -Integer.MAX_VALUE; int nextIndex = -1; for (int i = current + 1; i <= end; i++) { if (max < i + nums[i]) { max = i + nums[i]; nextIndex = i; } } stack.push(new Node(nextIndex, currentCount)); } return -1; } private static class Node{ private final int currentIndex; private final int count; private Node(int currentIndex, int count) { this.currentIndex = currentIndex; this.count = count; } } }
其解法一:
public int jump(int[] nums) { int end = 0; int maxPosition = 0; int steps = 0; for(int i = 0; i < nums.length - 1; i++){ //找能跳的最远的 maxPosition = Math.max(maxPosition, nums[i] + i); if( i == end){ //遇到边界,就更新边界,并且步数加一 end = maxPosition; steps++; } } return steps; }
这个代码最优秀的地方在于,用一轮循环最简洁的方式就完成了贪最大。其最值得我学习的地方,在于用一个end,加个判断,设立了一个边界的概念,
这样来代替回溯循环,格外的简洁明了。