045. Jump Game II
难度:Hard
刷题内容
原题连接
- 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.
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;
}
}
};