Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.数组
Determine if you are able to reach the last index.指针
For example: A = [2,3,1,1,4], return true.code
A = [3,2,1,0,4], return false.element
时间 O(N) 空间 O(1)leetcode
若是只是判断可否跳到终点,咱们只要在遍历数组的过程当中,更新每一个点能跳到最远的范围就好了,若是最后这个范围大于等于终点,就是能够跳到。get
public class Solution { public boolean canJump(int[] nums) { int max = 0, i = 0; for(i = 0; i <= max && i < nums.length; i++){ max = Math.max(max, nums[i] + i); } return i == nums.length; } }
Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.it
Your goal is to reach the last index in the minimum number of jumps.io
For example: Given array A = [2,3,1,1,4]ast
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)class
时间 O(N) 空间 O(1)
若是要计算最短的步数,就不能贪心每次都找最远距离了,由于有可能一开始跳的远的路径,后面反而更慢。因此咱们要探索全部的可能性,这里用快慢指针分出一块当前结点能跳的一块区域,而后再对这块区域遍历,找出这块区域能跳到的下一块区域的上下边界,每块区域都对应一步,直到上界超过终点时为之。
public class Solution { public int jump(int[] nums) { int high = 0, low = 0, preHigh = 0, step = 0; while(high < nums.length - 1){ step++; //记录下当前区域的上界,以便待会更新下一个区域的上界 preHigh = high; for(int i = low; i <= preHigh; i++){ //更新下一个区域的上界 high = Math.max(high, i + nums[i]); } //更新下一个区域的下界 low = preHigh + 1; } return step; } }
Q:若是要求返回最短跳跃路径,如何实现?A:能够使用DFS,并根据一个全局最短步数维护一个全局最短路径,当搜索完全部可能后返回这个全局最短路径。