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
.
刚开始是用dp做的, boolean[] dp , 假设 i,j都是有效的index并且 i > j, 则 dp[i] = dp[j] && (nums[j] >= (i - j)), 也就是说能跳到 i 的前提是前面有一个点 j 可以跳到, 并且从 j 能够跳到 i,对于每一个点都要遍历前面的点看有无有效点j, 所以复杂度是 O(n^2), 在leetcode中会TLE
public class Solution { public boolean canJump(int[] nums) { if(nums == null || nums.length == 0){ return false; } boolean[] dp = new boolean[nums.length]; dp[0] = true; for(int i = 1; i < nums.length; i++){ for(int j = 0; j < i; j++){ dp[i] = dp[j] && nums[j] >= (i - j); if(dp[i] == true){ break; } } } return dp[nums.length - 1]; } }
public class Solution { public boolean canJump(int[] nums) { if(nums == null || nums.length == 0){ return false; } int reach = 0; for(int i = 0; i <= reach && i < nums.length; i++){ reach = Math.max(nums[i] + i, reach); } if(reach < nums.length - 1){ return false; } return true; } }