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.
For example:
Given array 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.)
当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。时间复杂度仍然是O(n),空间复杂度也是O(1)。代码如下:
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size() == 0)
return 0;
int lastReach = 0;
int reach = 0;
int step = 0;
for(int i =0; i<=reach&&i<nums.size(); i++){
if(lastReach < i){
step++;
lastReach = reach;
}
reach = max(reach,nums[i]+i);
}
if(reach<nums.size()-1)
return 0;
return step;
}
};
45. Jump Game II
最新推荐文章于 2022-07-13 20:43:33 发布