55. Jump Game
by Botao Xiao
Question:
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.
Thinking:
- 使用贪心算法,对于每一个元素,我们都记录当前能到达的最远距离。
- 在记录的过程中,如果当前的元素无法被最远距离cover,就说明当前的元素不可即,return false.
class Solution {
public boolean canJump(int[] nums) {
if(nums == null || nums.length == 0) return false;
int len = nums.length;
int reach = nums[0];
for(int i = 0; i < len; i++){
if(reach < i) return false;
reach = Math.max(reach, i + nums[i]);
}
return true;
}
}
二刷
二刷的时候是直接从JUMP GAME II跳过来的,还是延续了那道题的思维模式,使用了slow,fast双指针,实际上没有这个必要。
class Solution {
public boolean canJump(int[] nums) {
if(nums == null || nums.length == 0 || nums.length == 1) return true;
int slow = 0, fast = 0, reach = 0;
for(int i = 0; i < nums.length; i++){
if(reach < i) return false;
else if(reach >= nums.length - 1) return true;
for(int j = slow; j <= fast; j++){
reach = Math.max(reach, j + nums[j]);
}
slow = fast + 1;
fast = reach;
}
return true;
}
}
Subscribe via RSS