原题链接在这里:
题目:
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
.
题解:
维护一个当前能跳到的最大值maxJump, 若是maxJump 已经>=nums.length-1, 说明能跳到最后一个点,return true.
若是过程中maxJump <= i, 说明跳到当前点便不能往前,跳出loop, return false.
Time Complexity: O(n). Space: O(1).
AC Java:
1 public class Solution { 2 public boolean canJump(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return false; 5 } 6 int maxJump = 0; 7 for(int i = 0; i= nums.length-1){10 return true;11 }12 if(maxJump <= i){13 break;14 }15 }16 return false;17 }18 }
下面的Method 2 更加模板化,方便于的操作。maxJump同样是需要维护的能跳到的最大值,每当 i 大于maxJump时就说明脱节了,
maxJump到不了i 不对maxJump做进一步更新。
loop后面检查maxJump 有没有到 最后一个元素,所示没到,就返回false, 到了就返回 true.
Time Complexity: O(n), Space O(1).
AC Java:
1 public class Solution { 2 public boolean canJump(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return false; 5 } 6 int maxJump = 0; 7 for(int i = 0; i