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 =
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.)
Solution 1:
public class Solution {
public int jump(int[] nums) {
int n=nums.length;
int step=0, max=0, next=0;
int i=0;
while (max<n-1) {
while (i<=max) {
next=Math.max(next,i+nums[i]);
i++;
}
step++;
max=next;
}
return step;
}
}
Solution 1: Cleaner code with for loop
public class Solution {
public int jump(int[] nums) {
int n=nums.length;
int step=0, max=0, next=0;
for (int i=0; i<n; i++) {
next=Math.max(next,i+nums[i]);
if (i==max && i!=n-1) {
max=next;
step++;
}
}
return step;
}
}
没有评论:
发表评论