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.)
分析:
从第一个点出发,步数为1;
对它可达的点中找到下一次能跳到的最远距离,此时步数+1;
依次类推,直到终点,步数为所求最小值。
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if(n == 1)
return 0;
int i = 0;
int count=1;
int reach = nums[0];
for(i = 1;i<n;i++)
{
if(reach >= n-1)
{
return count;
}
if(reach < i)
{
return INT_MAX;
}
int last_reach = reach;
int maxx = 0;
while(last_reach >= i)
{
if(maxx < (nums[i]+i))
{
maxx = nums[i]+i;
}
i++;
}
i--;
reach = maxx;
count++;
}
return count;
}
};