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.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: 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.
Note:
You can assume that you can always reach the last index.
Solution
计算每次移动一步的最远能够到达的距离。复杂度 O ( n ) O(n) O(n)
class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() < 2) {
return 0;
}
int min_road_length = 0, temp, current_index = 0, length = nums.size() - 1, max_index = 0;
max_index = nums[0];
while (max_index < length) {
while (current_index < max_index) {
max_index = max_index < nums[current_index] + current_index ? nums[current_index] + current_index : max_index;
++current_index;
}
min_road_length = min_road_length + 1;
}
return min_road_length;
}
};