难度Hard
原题连接
内容描述
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.
思路 - 时间复杂度: O(n)- 空间复杂度: O(1)*****
刚开始想到使用动态规划,时间复杂度为O(n),但是TLE了,其实可以在O(n)的时间复杂度内完成的。遍历数组,每次都走到在nums[i]的范围里能走到的最远的距离。记录ans。
class Solution {
public:
int jump(vector<int>& nums) {
int i = 0,length = nums.size(),next = nums[0],ans = 0;
if(length < 2)
return 0;
while(i < length)
{
++ans;
if(next >= length - 1)
return ans;
int current = i;
for(int j = current+1;j <= min(next,length - 1);++j)
{
i = max(i,nums[j] + j);
cout << i << " ";
}
swap(i,next);
cout << i << " "<< next << endl;
}
}
};