[Leetcode] 45. Jump Game II 解题报告
来源:互联网 发布:java 键值对会覆盖 编辑:程序博客网 时间:2024/05/16 02:18
题目:
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.
思路:
本质上是一道用贪心算法解决的题目,但是从实现上来看却感觉是动态规划的变种:我们维护一个当前可以到达的最远位置,以及一个一维数组(记录从首元素跳到该位置元素所需的最少步数),然后遍历nums中的每个元素,一旦通过它可以跳到更远的位置,则更新当前最远位置到更远位置之间的最少步数。一旦发现最远位置到达末尾或者越界,则可以立即返回。
我感觉对本题目的时间复杂度分析可能是面试官感兴趣的另一考点:虽然从实现上来看,里面存在两重循环,但实际的时间复杂度却是O(n)。这是因为:在我们对nums中的元素做遍历的过程中,所有更新的区间是不重合的,而且这些区间刚好完整覆盖了整个数组空间,所以总和是n。
代码:
class Solution {public: int jump(vector<int>& nums) { if(nums.size() == 0) return 0; vector<int> step(nums.size(), 0); int max_reach = 0; for(int i = 0; i < nums.size(); ++i) { int tem = nums[i] + i; // the maximum index one can reach from i if(max_reach < tem) { tem = min(tem, (int)nums.size() - 1); // avoid overflow for(int j = max_reach + 1; j <= tem; ++j) // we can reach [max_reach + 1, tem] in fewer steps step[j] = step[i] + 1; max_reach = tem; if(max_reach >= nums.size() -1) // we alrady reach the last element break; } } return step[nums.size() - 1]; }};
- [leetcode] 45. Jump Game II 解题报告
- leetcode解题报告:45. Jump Game II
- [Leetcode] 45. Jump Game II 解题报告
- Leetcode Jump Game II 解题报告
- 【LeetCode】Jump Game II 解题报告
- [LeetCode] Jump Game II 解题报告
- Leetcode #45. Jump Game II 跳跃游戏2 解题报告
- Leetcode Jump Game 解题报告
- 【LeetCode】Jump Game 解题报告
- [LeetCode] Jump Game 解题报告
- [leetcode] 55. Jump Game 解题报告
- LeetCode解题报告 55. Jump Game [medium]
- [Leetcode] 55. Jump Game 解题报告
- LeetCode 55. Jump Game 解题报告
- leetcode解题方案--045-- Jump Game II
- leetcode解题之45. Jump Game II&55. Jump Game java (跳跃游戏)
- LeetCode --- 45. Jump Game II
- LeetCode 45.Jump Game II
- 13-Oracle入门之插入操作
- hdu2054 判断俩数是否相等
- python pip的一些用法
- 16秋《计算机网络技术》作业3
- QtCreator 4.0 Q5.7 VS2015 源码中有中文导致编译失败的问题的解决方法
- [Leetcode] 45. Jump Game II 解题报告
- 16秋《计算机网络技术》作业2
- LeetCode 169——分治算法使用
- 16秋《计算机网络技术》作业1
- 442. Find All Duplicates in an Array
- 从源码的角度分析Handler机
- apache与tomcat的联系与区别
- Android 取消 上一个Toast
- mac上expect安装