最少跳跃数(II)
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置,(假设你总是能到达最后一个位置)。
public int jump(int[] nums) {
int position = nums.length - 1; //要找的位置
int steps = 0;
while (position != 0) { //是否到了第 0 个位置
for (int i = 0; i < position; i++) {
if (nums[i]+i >= position) {
position = i; //更新要找的位置
steps++;
break;
}
}
}
return steps;
}
方法二:
public int jump(int[] arr){
if(arr==null||arr.length==0){
return 0;
}
int jump= 0;
int cur = 0;
int next = 0;
for(int i=0;i<arr.length;i++){
if(cur<i){
jump++;
cur = next;
}
next = Math.max(next, i+arr[i]);
}
return jump;
}
最少跳跃数(跳跃游戏I)
给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
public class Solution {
public boolean canJump(int[] nums) {
int n = nums.length;
int rightmost = 0;
for (int i = 0; i < n; ++i) {
//只要i于rightmost就能往前跳跃
if (i <= rightmost) {
rightmost = Math.max(rightmost, i + nums[i]);
if (rightmost >= n - 1) {
return true;
}
}
}
return false;
}
}