给定一个非负整数数组nums,假定最开始处于下标为0的位置,数组里面的每个元素代表下一跳能够跳跃的最大长度。如果能够跳到数组最后一个位置,则返回true,否则返回false。
数据范围:
[2,1,3,3,0,0,100]
true
首先位于nums[0]=2,然后可以跳2步,到nums[2]=3的位置,再跳到nums[3]=3的位置,再直接跳到nums[6]=100,可以跳到最后,返回true
[2,1,3,2,0,0,100]
false
无论怎么样,都跳不到nums[6]=100的位置
用一个变量记录能到达的最大下标,maxindex = i + nums[i].结束循环的时候判断该下标是否到达数组最后即可。
import java.util.*; public class Solution { public boolean canJump (int[] nums) { int maxindex = 0; for(int i = 0; i < nums.length && i <= maxindex; ++i) { maxindex = Math.max(maxindex, i + nums[i]); if(maxindex >= nums.length - 1)return true; } return maxindex >= nums.length - 1; } }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return bool布尔型 */ public boolean canJump (int[] nums) { // write code here //最大跳远距离 int maxReach=0; //循环维护最大跳转距离 for(int i=0;i<nums.length;i++){ //如果最大跳远距离无法到达该点为false if(maxReach<i){ return false; } //如果最大跳远距离大等于目标位置为true if(maxReach>=nums.length-1){ return true; } //遍历每个节点,只要该节点的跳远距离大于maxReach,就更新maxReach maxReach=Math.max(maxReach,i+nums[i]); } return true; } }
package main import _"fmt" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return bool布尔型 */ func canJump( nums []int ) bool { n:=len(nums) end:=0 for i:=0;i<n;i++{ if end<i{ return false } end=max(end,i+nums[i]) } return true } func max(a,b int)int{ if a>b{ return a } return b }
public boolean canJump (int[] nums) { // write code here int len = nums.length; int end = 0; for (int i = 0; i < len; i++) { if (i > end) return false; end = Math.max(end,i + nums[i]); } return true; }
//贪心策略:在cover范围内移动,不断更新cover范围,若可以覆盖整个范围,那么最后点可达 //直白说,就是每次取最大覆盖范围,最后就可以取到全局最大范围 bool canJump(vector<int>& nums) { // write code here int cover=0;//在没跳的时候,只能从下标为0的地方开始跳,就覆盖范围为0 for(int i=0;i<=cover;i++) { cover=max(cover,i+nums[i]); if(cover>=nums.size()-1) return true; } return false; }