leetcode45. Jump Game II
来源:互联网 发布:windows怎么取消共享 编辑:程序博客网 时间:2024/06/04 19:37
45. Jump Game II
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.
Your goal is to reach the last index in the minimum number of jumps.
For example:Given array A = [2,3,1,1,4]The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)Note:You can assume that you can always reach the last index.
解法一
step[i]表示跳到这步最少需要几步。step[i]每次取 step[i] = Math.min(step[i], step[j] + 1),j为小于等于i的位置。
时间复杂度为O(n),超时。
public class Solution { public int jump(int[] nums) { if (nums == null || nums.length == 0) { return 0; } // state int[] step = new int[nums.length]; // initialize step[0] = 0; for (int i = 1; i < nums.length; i++) { step[i] = Integer.MAX_VALUE; } for (int i = 0; i < nums.length; i++) { for (int j = 0; j < i; j++) { if (step[j] != Integer.MAX_VALUE && j + nums[j] >= i) { step[i] = Math.min(step[i], step[j] + 1); } } } return step[nums.length - 1]; }}
解法二
贪心算法:每一次跳跃都有一个范围,每次记录最远到达的位置farthest。下一次的start为end+1,end=farest,即为上一跳所能跳到的范围。然后再循环范围内的位置,找到最远的位置。直到某一跳达到最后一个位置停止,每一跳+1。
public class Solution { public int jump(int[] nums) { if (nums == null || nums.length == 0) { return -1; } int start = 0, end = 0, jumps = 0; while (end < nums.length - 1) { jumps++; int farthest = end; for (int i = start; i <= end; i++) { if (nums[i] + i > farthest) { farthest = nums[i] + i; } } start = end + 1; end = farthest; } return jumps; }}
0 0
- [LeetCode45]Jump Game II
- Leetcode45 Jump Game II
- leetcode45 Jump Game II
- LeetCode45. Jump Game II
- LeetCode45. Jump Game II
- leetcode45. Jump Game II
- Leetcode45. Jump Game II
- LeetCode45. Jump Game II
- LeetCode45 Jump Game II【贪心】
- LeetCode45——Jump Game II
- Jump Game &Jump Game II
- Jump Game/Jump Game II
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- 登录验证
- 如何在 Java 中正确使用 wait, notify 和 notifyAll – 以生产者消费者模型为例
- java.util.concurrent.ReentrantLock
- C++STL学习笔记
- 关于闭包问题的多种方法
- leetcode45. Jump Game II
- HDU 1841 Find the Shortest Common Superstring(KMP)
- 《大话设计模式》讨论
- CUDA driver version is insufficient for CUDA runtime version
- 这是我在南航读研第一年末,写下了第一篇博客
- JAVA 消息队列的使用场景
- 【Anaconda】conda环境管理和包管理
- C# 获取Post或Get返回的网页
- Android系统启动过程