【LeetCode】45. Jump Game II (Hard)
来源:互联网 发布:web前端后端数据交互 编辑:程序博客网 时间:2024/03/29 21:41
【题目】
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.)
You can assume that you can always reach the last index.
【解】
从最后的位置往前推,贪心记录能到达这个位置的最靠前的一个的下标。
A = [2, 3, 1, 1, 4],对应的 V = [-1, 0, 0, 1, 1]
然后从后往前推,数几步能到第一个位置(-1)
求V:从第一个数开始,A[0] = 2,能到达的位置有0, 1和2,然后下一个数A[0] = 3,0, 1, 2这3个位置已经可以从位置0达到,所以从位置3开始看能否达到,然后给V赋值......
给V赋值的时候只顺序做了一次,所以时间复杂度应该是O(n)? ,空间复杂度O(n)
class Solution {public: int jump(vector<int>& nums) { int n = nums.size(); vector<int> v(n); v[0] = -1; int t = 0; for (int i = 0; i < n; i++) { int a = nums[i]; if (a + i > t) { int j; for (j = t + 1; j <= a + i && j < n; j++) { v[j] = i; } t = j - 1; } } int i = v[n - 1]; int cnt = 0; while (i != -1) { i = v[i]; cnt++; } return cnt; }};
- 【LeetCode】45. Jump Game II (Hard)
- Leetcode 45. Jump Game II (Hard) (cpp)
- LeetCode hard 45. Jump Game II
- 45. Jump Game II Hard
- leetcode hard模式专杀之45. Jump Game II
- [Leetcode 45, Hard] Jump Game II
- Hard-题目23:45. Jump Game II
- LeetCode --- 45. Jump Game II
- LeetCode 45.Jump Game II
- [Leetcode] 45. Jump Game II
- [leetcode] 45.Jump Game II
- [leetcode] 45.Jump Game II
- leetcode 45. Jump Game II
- LeetCode 45. Jump Game II
- LeetCode 45. Jump Game II
- leetcode.45. Jump Game II
- leetcode 45. Jump Game II
- leetcode 45. Jump Game II
- sdut 走迷宫
- camera 2 连拍
- 51nod 1490 多重游戏
- tmux
- HBase内置过滤器的一些总结
- 【LeetCode】45. Jump Game II (Hard)
- Unity3D自学笔记——UGUI背包系统(八)物品的分类与整理
- Semantic Web Technologies: RDFS Inference
- OJ_1186数学公式【在化简分数时调用函数进行化简】【简便方法】
- 基于可靠消息的分布式事务错误处理
- 高并发性能的提升
- 错位排列的魅力
- SQL语句之CASE WHEN
- int 和 Integer 的区别