[LeetCode]Jump Game
2016-10-24 16:54
274 查看
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.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
本题难度。有2种算法分别是:双指针法和贪心法。
1、双指针法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
与Jump Game II的双指针法一样。不过题目Jump Game II有个前提是它一定能跳到最后一个元素;而这里是不一定能跳到最后。不能跳到最后只有一种可能:原地踏步。所以我用11-12行来判断。
【代码】
2、贪心法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
如果只是判断能否跳到终点,我们只要在遍历数组的过程中,更新每个点能跳到最远的范围就行了,如果最后这个范围大于等于终点,就是可以跳到。
【代码】
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.
本题难度。有2种算法分别是:双指针法和贪心法。
1、双指针法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
与Jump Game II的双指针法一样。不过题目Jump Game II有个前提是它一定能跳到最后一个元素;而这里是不一定能跳到最后。不能跳到最后只有一种可能:原地踏步。所以我用11-12行来判断。
【代码】
public class Solution { public boolean canJump(int[] nums) { //require int size=nums.length; int high=0,low=0,preHigh=0; while(high<size-1){ preHigh=high; for(int i=low;i<=preHigh;i++) high=Math.max(high,nums[i]+i); low=preHigh+1; if(high==preHigh) return false; } //ensure return true; } }
2、贪心法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
如果只是判断能否跳到终点,我们只要在遍历数组的过程中,更新每个点能跳到最远的范围就行了,如果最后这个范围大于等于终点,就是可以跳到。
【代码】
public class Solution { public boolean canJump(int[] nums) { int max = 0, i = 0; for(i = 0; i <= max && i < nums.length; i++){ max = Math.max(max, nums[i] + i); } return i == nums.length; } }
参考
Jump Game I相关文章推荐
- leetcode-Jump Game
- leetcode -- Jump Game
- leetcode(55). Jump Game
- leetcode:Jump Game 【Java】
- LeetCode刷题笔录Jump Game
- [array] leetcode-55. Jump Game - Medium
- LeetCode:Jump Game
- [LeetCode] Jump Game
- LeetCode-Jump Game
- LeetCode:Jump Game
- 【LeetCode】(55)Jump Game(Medium)
- [leetcode] Jump Game
- [leetcode]Jump Game
- LeetCode(55)Jump Game
- leetcode---Jump Game---贪心
- Leetcode-Jump Game
- LeetCode 55. Jump Game(跳跃游戏Ⅰ)
- Jump Game 的三种思路 - leetcode 55. Jump Game
- Leetcode 55. Jump Game (Medium) (cpp)
- [LeetCode] Jump Game 解题报告