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 =
Given array A =
[2,3,1,1,4]
The minimum number of jumps to reach the last index is
Hint: a follow-up question of Jump Game. Use greedy. Keep updating the farthest position you can reach. If the farthest position after one iteration still cannot get to the end of the array, your step will be added by one.2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Java语言: JumpGameII
01 public int jump(int[] A) {
02 if(A.length<=1)
03 return 0;
04 int start=1;
05 int end=A[0];
06 int minstep=1;
07 while(end<A.length-1)
08 {
09 //have not reach the end, proceed
10 minstep++;
11 int farthest=end;
12 //update the farthest pos it can reach
13 for(int i=start;i<=end;i++)
14 {
15 if(A[i]+i>farthest)
16 {
17 farthest=A[i]+i;
18 }
19 }
20 start=end+1;
21 if(farthest<start)
22 return -1;
23 end=farthest;
24 }
25 return minstep;
26 }
02 if(A.length<=1)
03 return 0;
04 int start=1;
05 int end=A[0];
06 int minstep=1;
07 while(end<A.length-1)
08 {
09 //have not reach the end, proceed
10 minstep++;
11 int farthest=end;
12 //update the farthest pos it can reach
13 for(int i=start;i<=end;i++)
14 {
15 if(A[i]+i>farthest)
16 {
17 farthest=A[i]+i;
18 }
19 }
20 start=end+1;
21 if(farthest<start)
22 return -1;
23 end=farthest;
24 }
25 return minstep;
26 }
没有评论:
发表评论