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.)
题意:给出一个非负数组,求从数组下标0到尾的最小步数。
思路:在当前步有可移动区间[l,r],计算当前步的最大下标。如果下标大于r,步数加1,更新[l,r],代码如下
class Solution {
public int jump(int[] nums)
{
if (nums.length == 0 || nums.length < 2) return 0;
int step = 1;
int l = 0;
int r = nums[0];
while (l <= r)
{
if (r >= nums.length - 1)
{
return step;
}
int max = Integer.MIN_VALUE;
for (; l <= r; l++)
{
max = Math.max(max, l + nums[l]);
}
if (max > r)
{
step++;
l = r;
r = max;
}
}
return -1;
}
}