class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size()==1)
return 0;
int max=nums[0],range=nums[0];
int step=0;
//loop the array for only once
for(int i=1;i<nums.size();i++)
{
//the range of one number can cover the last index
if(range>=nums.size()-1)
{
step++;
break;
}
//find the maximum number in the current range
if(nums[i]+i>max)
max=nums[i]+i;
//the loop reaches one range, update to a new range
if(i==range)
{
step++;
//some number in the range is bigger than the first one
if(max>range)
range=max;
//the first number is the biggest among its range
else
range=nums[i]+i;
}
}
return step;
}
};
leetcode 45: Jump Game II
最新推荐文章于 2019-05-02 20:40:21 发布