45. Jump Game II
problem description
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.algorithm thought
code
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size()<2)
return 0;
int res=1;
int maxstep=nums[0];
int tmpstep=nums[0];
for(int i=1;i<nums.size()-1;++i){
tmpstep=max(tmpstep,i+nums[i]);
if(i==maxstep){
res++;
maxstep=tmpstep;
}
}
return res;
}
};algorithm analysis
Last updated