给定一个非负整数数组nums,假定最开始处于下标为0的位置,数组里面的每个元素代表下一跳能够跳跃的最大长度。请你判断最少跳几次能跳到数组最后一个位置。
1.如果跳不到数组最后一个位置或者无法跳跃(即数组长度为0),请返回-1
2.数据保证返回的结果不会超过整形范围,即不会超过
数据范围:
第一行输入一个正整数 n 表示数组 nums的长度第二行输入 n 个整数,表示数组 nums 的内容
输出最少跳几次到最后一个位置
7 2 1 3 3 0 0 100
3
首先位于nums[0]=2,然后可以跳2步,到nums[2]=3的位置,step=1再跳到nums[3]=3的位置,step=2再直接跳到nums[6]=100,可以跳到最后,step=3,返回3
7 2 1 3 2 0 0 100
-1
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int[] array = new int[n]; for(int i = 0; i < n; i++) { array[i] = in.nextInt(); } if(n == 0) { System.out.println(-1); } else { int res = jumpingGame(array); System.out.println(res); } } } public static int jumpingGame(int[] array) { int n = array.length; int[] dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for(int i = 0; i < array.length - 1; i++) { int temp = array[i]; if(dp[i] == Integer.MAX_VALUE || temp == 0) { continue; } // 更新跳到 i + 1, i + 2 ... i + temp 所需跳数, // 如果 i + temp 大于 n - 1, 那么只需要更新到 n - 1 即可 for(int j = 1; j <= temp; j++) { if(i + j < n) { // 如果 i+j 位置所需跳数为 Integer.MAX_VALUE, // 直接更新为 dp[i] + 1,否则就取 max(dp[i+j],dp[i]+1) if(dp[i + j] != Integer.MAX_VALUE) { dp[i + j] = Math.min(dp[i + j], dp[i] + 1); } else { dp[i + j] = dp[i] + 1; } } else { break; } } } // 最后一个位置的状态如果不为 Integer.MAX_VALUE, 就直接返回, // 否则说明跳不到该位置, 返回 -1 return dp[n - 1] == Integer.MAX_VALUE ? -1 : dp[n - 1]; } }
import java.util.*; public class Main{ public static void main(String[]args){ Scanner sc=new Scanner(System.in); int n =sc.nextInt(); int[]nums=new int[n]; for(int i=0;i<n;i++){ nums[i]=sc.nextInt(); } int edge=0,cur=0; int cnt=0; for(int i=0;i<n;i++){ if(i>edge){ System.out.println(-1); return; } edge=Math.max(edge,nums[i]+i); if(cur==i&&i!=n-1){ cnt++; cur=edge; } } System.out.println(cnt); } }