*LeetCode--55. Jump Game
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
题目大意:给定一个数组,数组元素代表该位置能向前最多走几步,确定是否能够从开头走到结尾。
方法1:
//只有在含有0的时候才可能到不了最后。因此,在遇到0时,依次查看0之前的元素,看是否能跳过0 public static boolean canJump(int[] nums) { if(nums ==null) return false; if(nums.length==1) return true; int end = nums.length-1; //最后的位置helper int i=0; int j ; while(i<end){ for(; i < end ; i++){ if(nums[i]==0) break; else if(nums[i]+i>=end) return true; } if(i==end) return true; for(j = i-1 ; j >= 0 ; j--){ if(nums[j]+j>i) break; } if(j==-1) return false; i++; } return true; }
方法2:
//从前向后,将数组更新为看每个元素最远还能向前移动几步。如果有一个为0了,说明不能向前再移动了。 public static boolean canJump2(int[] nums) { if(nums ==null||nums[0]==0&&nums.length!=1) return false; if(nums.length==1) return true; int end = nums.length; //最后的位置helper for(int i = 1 ; i < end ;i++){ nums[i] = Math.max(nums[i], nums[i-1]-1); //更新为每个元素最远能向前几步 if(nums[i]==0&&i<end-1) return false ; } return true; }
方法3:
//从后向前,看last能不能推到开头 public static boolean canJump3(int[] nums) { if(nums ==null||nums[0]==0&&nums.length!=1) return false; int len = nums.length; int last = len-1; for(int i = len-2 ; i >=0 ; i--){ if(nums[i]+i>=last) last = i; } return last<=0; }
上面三种方法均能通过
还有一种:采用递归(特殊情况不能通过,超时!!!!!!)
//不能通过,特殊情况的时候超时!!!!!!!!!!!!!!!!!!!!! public static boolean canJump(int[] nums) { if(nums ==null) return false; if(nums.length==1) return true; int end = nums.length; //最后的位置helper return helper(nums,0,end-1); } public static boolean helper(int[] nums,int start, int sum ){ if(nums[start]>=sum) return true; else{ int temp = nums[start]; for(int i = temp ; i>0 ; i--){ if(true==helper(nums,start+i,sum-i)) return true; } return false; } }

浙公网安备 33010602011771号