標籤:style blog http color os io for ar
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. (Jump 1 step from index 0 to 1, then 3 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 }