题目描述:给定一个非负整数数组,你最初位于数组的第一个位置。java
数组中的每一个元素表明你在该位置能够跳跃的最大长度。segmentfault
你的目标是使用最少的跳跃次数到达数组的最后一个位置。数组
假设你老是能够到达数组的最后一个位置。网络
示例说明请见LeetCode官网。url
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/probl...
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。code
- 首先,若是nums的长度为1,由于不须要走,直接返回0;
- 若是nums的长度为2,因为必定能够到达最后一个位置,并且至少须要一步,直接返回1;
当不是前两种状况时,首先,声明一个变量length为数组最大的索引位,声明一个变量result记录最少的跳跃次数,初始化为最大的的int值,声明一个HashMap为toJumpTimes记录跳跃过的位置和相应跳跃到该位置最少的步数,声明一个队列toJump记录当前走到的位置,声明一个队列times同步记录走到当前位置须要的步数,首先,将0加入到jumped和times,而后遍历队列toJump按照如下过程处理:索引
- 从队列中取出一位cur;
- 若是cur对应的数组的值为0,则跳过处理下一个队列中的值;
- 判断toJumpTimes中是否存在该位置的索引,若是存在且走到当前位置的步数多于其余走法走到当前位置的步数,则跳过处理下一个;
- 若是cur对应的数组的值大于等于
length-cur
便可以从当前位置直接跳跃到最后一位,则判断若是当前的跳跃次数小于result,则更新result的值;不然,若是当前跳跃次数不小于result,则跳过处理下一个;若是当前跳跃次数小于result,则将
cur+1 ~ cur+nums[cur]
索引位添加到toJump,添加以前须要判断toJumpTimes的key中是否存在当前索引位:队列
- 若是不存在而且当前跳跃次数小于result,则把当前索引位和相应的跳跃次数添加到toJump和times和toJumpTimes;
- 若是存在而且当前跳跃次数小于最小的跳跃次数,则把当前索引位和相应的跳跃次数添加到toJump和times,而且更新当前索引位在toJumpTimes中的最少跳跃次数。
最后,返回result即为最少跳跃次数。游戏
说明:处理方法相似于 LeetCode-055-跳跃游戏 这道题目。leetcode
import java.util.*; public class LeetCode_045 { public static int jump(int[] nums) { if (nums.length == 1) { return 0; } if (nums.length == 2) { return 1; } int result = Integer.MAX_VALUE; int length = nums.length - 1; // 定义走到过的位置,而且记录走到当前位置最少的步数 Map<Integer, Integer> toJumpTimes = new HashMap<>(); toJumpTimes.put(0, 0); // 定义当前到的位置 Stack<Integer> toJump = new Stack<>(); Stack<Integer> times = new Stack<>(); toJump.push(0); times.push(0); while (!toJump.isEmpty()) { Integer cur = toJump.pop(); Integer curTimes = toJumpTimes.get(cur); if (nums[cur] == 0) { continue; } // 判重,若是走到当前位置的步数多于其余走法走到当前位置的步数,则跳过处理下一个 if (toJumpTimes.containsKey(cur) && curTimes > toJumpTimes.get(cur)) { continue; } if (nums[cur] >= length - cur) { if (curTimes + 1 < result) { result = curTimes + 1; } } else { if (curTimes + 1 >= result) { continue; } for (int i = 1; i <= nums[cur]; i++) { if (!toJumpTimes.containsKey(cur + i)) { if (curTimes + 1 < result) { toJumpTimes.put(cur + i, curTimes + 1); toJump.push(cur + i); times.push(curTimes + 1); } } else { Integer time = toJumpTimes.get(cur + i); if (curTimes + 1 < time) { toJumpTimes.put(cur + i, curTimes + 1); toJump.push(cur + i); times.push(curTimes + 1); } } } } } return result; } public static void main(String[] args) { int[] nums = new int[]{2, 3, 1, 1, 4}; System.out.println(jump(nums)); } }
【每日寄语】 要铭记在心:天天都是一年中最美好的日子。