LEETCODE 45. Jump Game II
题目大意
给出一个正整数数组,每个元素代表当前位置所能跳转的最大步数,求能到达数组最后的的最少跳转次数,实际上是44题的一个变种,44题只是判断能否到达数组最后,本题多加一个要记录最少跳转次数的要求。
例如
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.)
解题思路
也是贪心策略,记录所能到达最大下标,并且在更新最大下标的时候更新最小步数,当最大下标大于等于数组最后的时候,直接返回这个最小步数
实现代码
超时
class Solution {
public:
int jump(vector<int>& nums) {
const int arraySize = int(nums.size());
int timesArray[arraySize];
int rightBound = 1, leftBound = 0;
for (int i = 1; i < arraySize; i++) {
timesArray[i] = INT_MAX;
}
timesArray[0] = 0;
while (leftBound < arraySize) {
int newRightBound = rightBound;
for (int i = leftBound; i < rightBound && i < arraySize; i++) {
for (int j = 1; j <= nums[i]; j++) {
if (i + j + 1 > newRightBound) {
newRightBound = i + j + 1;
}
if (i + j < arraySize && timesArray[i] + 1 < timesArray[i + j]) {
timesArray[i + j] = timesArray[i] + 1;
}
if (i + j >= arraySize && timesArray[i] + 1 < timesArray[arraySize - 1]) {
timesArray[arraySize - 1] = timesArray[i] + 1;
}
}
}
if (rightBound == newRightBound) {
return newRightBound >= arraySize - 1?timesArray[arraySize - 1]:0;
}
leftBound = rightBound;
rightBound = newRightBound;
}
return timesArray[arraySize - 1];
}
};
改善
class Solution {
public:
int jump(vector<int>& nums) {
int index = 0, rightBound = 0, maxInd = nums[0], minStep = 1;
while (index < nums.size() - 1 && index <= rightBound) {
for (int i = index; i <= rightBound; i++) {
maxInd = max(maxInd, i + nums[i]);
}
index = rightBound + 1;
if (maxInd > rightBound) {
if (maxInd >= nums.size() - 1) {
return minStep;
}
minStep++;
rightBound = maxInd;
} else {
break;
}
}
return 0;
}
};