首页 > 代码库 > [leetcode]Jump Game II
[leetcode]Jump Game II
Jump Game II
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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A =[2,3,1,1,4]
The minimum number of jumps to reach the last index is
2
. (Jump1
step from index 0 to 1, then3
steps to the last index.)
算法思路:
与[leetcode]Jump Game类似,不过数组不仅仅记录可达性,要记录最短路由跳数。思想一样。
例如[25000,24999,24998,24997,24996,24995,24994,24993......1]这个栗子,如果不记录最远可达(approach)的话,重复计算,势必超时
代码如下:
1 public class Solution { 2 public int jump(int[] a) { 3 if(a == null || a.length < 2) return 0; 4 int[] step = new int[a.length]; 5 for(int i = 1; i < a.length; i++){ 6 step[i] = a.length; 7 } 8 int approach = 0; 9 for(int i = 0; i < a.length; i++){10 int cover = i + a[i];11 if(cover <= approach) continue;12 for(int j = approach; j <= Math.min(cover,a.length - 1); j++){13 step[j] = Math.min(step[i] + 1,step[j]);14 }15 approach = i + a[i];16 }17 return step[a.length - 1];18 }19 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。