原题链接:https://leetcode.com/problems/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.)
Solution: 这道题可以使用贪心法来求解,对当前所在位置current,它下一步所能到达位置的范围是[current + 1, current + A[current]。我们在这个区间中选择一个位置作为下一步的终点next,使得在区间[current + 1, current + A[current]中,next能走的下一步最远(也就是next + A[next]的值最大)。这样,通过每一步选择能走最远的索引值,找到最小步数。
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if (n == 1) return 0;
int nextIndex = 0; // 下一步要去的地方
int maxIndex = 0; // 下一步能到达的最远的地方
int steps = 0;
for (int i = 0; i < n; ) {
int s = i + 1;
int e = min(i + nums[i], n-1);
if (e == n-1) return steps + 1;
while (s <= e) {
if ((s + nums[s]) > maxIndex) {
nextIndex = s;
maxIndex = s + nums[s];
}
s++;
}
i = nextIndex;
steps++;
}
}
};
算法分析: 当选择的下一步终点next的值在区间[current + 1, current + A[current]的靠左位置,则为next寻找下一步时,会造成大量的重复操作。
改进:
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size(), step = 0, start = 0, end = 0;
while (end < n - 1) {
step++;
int maxend = end + 1;
for (int i = start; i <= end; i++) {
if (i + nums[i] >= n - 1) return step;
maxend = max(maxend, i + nums[i]);
}
start = end + 1;
end = maxend;
}
return step;
}
};