问题描述:
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.)
解题思路:
max_i:表示已经可以到达的最远距离。
min_step:表示当前所走的最少步数。
max_len:表示min_step+1步可以到达的最远距离。
对于每个数组元素,需要考虑如下条件:
1、从当前位置可以到达的最远距离(A[i]+i)小于或等于之前的max_len,并且i没有达到max_i,那么什么也不需要做;
2、如果A[i]+i小于或等于之前的max_len,并且i等于max_i,那么就需要更新max_i的值,并且将min_step加1;
3、如果A[i]+i大于之前的max_len,并且A[i]+i能到达数组尾,那么,如果max_i大于当前的i值,则返回min_step+2。
4、如果A[i]+i大于之前的max_len,并且A[i]+i不能到达数组尾,呢么,如果max_i等于i,则更新max_i的值并将min_step加1,否则什么也不做,继续下一轮循环。
class Solution {
public:
int jump(int A[], int n) {
if ((0 == n) || (n == 1)) return 0;
int max_len = 0;/* 当前能跳的最远距离 */
int min_step = 0;/* 表示到当前位置最小的跳数 */
int max_i = A[0];/* 当前一步,达到最大的跨度的下标 */
for (int i = 0; i < n; i++) {
if ((A[i]+i <= max_len) && (i != max_i))
continue;
else if (A[i]+i <= max_len) {/* reach current scop */
max_i = max_len;
min_step++;
}
else if (A[i]+i > max_len) {
max_len = A[i]+i;
if (i == max_i) {
max_i = max_len;
min_step++;
}
if (max_len >= n-1) {
if (n-1 > max_i)
min_step++;
return (++min_step);
}
}
}
}
};
如下的解决思路和我的差不多,不过要比我的代码简洁很多:
/*
* We use "last" to keep track of the maximum distance that has been reached
* by using the minimum steps "ret", whereas "curr" is the maximum distance
* that can be reached by using "ret+1" steps. Thus,
* curr = max(i+A[i]) where 0 <= i <= last.
*/
class Solution {
public:
int jump(int A[], int n) {
int ret = 0;
int last = 0;
int curr = 0;
for (int i = 0; i < n; ++i) {
if (i > last) {
last = curr;
++ret;
}
curr = max(curr, i+A[i]);
}
return ret;
}
};