LeetCode 55. Jump Game
原题链接在这里:https://leetcode.com/problems/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.
Example 1:
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
题解:
maxJump是需要维护的能跳到的最大值,每当 i 大于maxJump时就说明脱节了.
maxJump到不了i 不对maxJump做进一步更新。
loop后面检查maxJump 有没有到 最后一个元素,所示没到,就返回false, 到了就返回 true.
Time Complexity: O(n), Space O(1).
AC Java:
1 class Solution { 2 public boolean canJump(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return true; 5 } 6 7 int maxJump = 0; 8 for(int i = 0; i < nums.length && i <= maxJump; i++){ 9 maxJump = Math.max(maxJump, i + nums[i]); 10 } 11 12 return maxJump >= nums.length - 1; 13 } 14 }