标签:
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.)
自己写的,超时了QAQ,就说hard的题怎么可能这么简单T_T。
package leetcode2; public class jumpgame2 { public static int jumpgame(int[] A){ int count=0; if(A[0]==0){ return 0; } int i=0; while(i<A.length-1){ int maxstep=i+1; int max=0; for(int j=1;j<A[i];j++){ if(i+j<A.length-1){ if(A[i+j]>=max){ max=A[i+j]; maxstep=j+i; } }else{ return count+1; } } i=maxstep; count++; } return count; } public static void main(String[] args) { // TODO Auto-generated method stub int[] a={2,5,1,1,4}; System.out.print("result is "+jumpgame(a)); } }
正确代码:dp
public int jump(int[] A) { if(A==null || A.length==0) return 0; int lastReach = 0; int reach = 0; int step = 0; for(int i=0;i<=reach&&i<A.length;i++) { if(i>lastReach) { step++; lastReach = reach; } reach = Math.max(reach,A[i]+i); //A[i]+i是最大能到的下一步!! } if(reach<A.length-1) return 0; return step; }
标签:
原文地址:http://www.cnblogs.com/joannacode/p/4413485.html