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.)
思路:
本能的想法仍然是动规,但是还是会超时。考虑在Jump Game的基础上进行更改,reach记录当前可到的最远距离,nextreach表示如果再走一步可到的最远距离,然后进行一次遍历,当reach不能满足要求时step加一,更新reach为nextreach。
代码:
1 int max(int a, int b){ 2 if(a > b) 3 return a; 4 return b; 5 } 6 int jump(int A[], int n) { 7 // IMPORTANT: Please reset any member data you declared, as 8 // the same Solution instance will be reused for each test case. 9 if(n <= 1) 10 return 0; 11 int reach=A[0], nextreach=A[0]; 12 int i; 13 int step=1; 14 for(i = 1; i < n; i++){ 15 if(i > reach){ 16 reach = nextreach; 17 step++; 18 } 19 nextreach = max(nextreach, i+A[i]); 20 } 21 return step; 22 }