LEETCODE 45. Jump Game II
来源:互联网 发布:lte中mr优化案例 编辑:程序博客网 时间:2024/06/06 23:56
LEETCODE 45. Jump Game II
题目大意
给出一个正整数数组,每个元素代表当前位置所能跳转的最大步数,求能到达数组最后的的最少跳转次数,实际上是44题的一个变种,44题只是判断能否到达数组最后,本题多加一个要记录最少跳转次数的要求。
例如
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.)
解题思路
也是贪心策略,记录所能到达最大下标,并且在更新最大下标的时候更新最小步数,当最大下标大于等于数组最后的时候,直接返回这个最小步数
实现代码
超时
class Solution {public: int jump(vector<int>& nums) { const int arraySize = int(nums.size()); int timesArray[arraySize]; int rightBound = 1, leftBound = 0; for (int i = 1; i < arraySize; i++) { timesArray[i] = INT_MAX; } timesArray[0] = 0; while (leftBound < arraySize) { int newRightBound = rightBound; for (int i = leftBound; i < rightBound && i < arraySize; i++) { for (int j = 1; j <= nums[i]; j++) { if (i + j + 1 > newRightBound) { newRightBound = i + j + 1; } if (i + j < arraySize && timesArray[i] + 1 < timesArray[i + j]) { timesArray[i + j] = timesArray[i] + 1; } if (i + j >= arraySize && timesArray[i] + 1 < timesArray[arraySize - 1]) { timesArray[arraySize - 1] = timesArray[i] + 1; } } } if (rightBound == newRightBound) { return newRightBound >= arraySize - 1?timesArray[arraySize - 1]:0; } leftBound = rightBound; rightBound = newRightBound; } return timesArray[arraySize - 1]; }};
改善
class Solution {public: int jump(vector<int>& nums) { int index = 0, rightBound = 0, maxInd = nums[0], minStep = 1; while (index < nums.size() - 1 && index <= rightBound) { for (int i = index; i <= rightBound; i++) { maxInd = max(maxInd, i + nums[i]); } index = rightBound + 1; if (maxInd > rightBound) { if (maxInd >= nums.size() - 1) { return minStep; } minStep++; rightBound = maxInd; } else { break; } } return 0; }};
0 0
- 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
- [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
- C++基础积累(1)using namespace potter 自定义命名空间和使用
- JSON.parse()和JSON.stringify()
- [BZOJ3837][Pa2013][随机][乱搞]Filary
- python文件处理:解析.xml文件
- JAVA类C++指针使用
- LEETCODE 45. Jump Game II
- IDOC的处理函数IDOC_INPUT_ORDERS的增强点的分析
- Android 使用极光/友盟推送,APP进程杀死后为什么收不到推送
- Android实现倒计时功能
- 给ProgressBar 设置圆形进度条颜色
- Xposed入门浅析
- oracle dead lock
- 帧动画的实现
- 导出数据库中的表为PDF格式(freemark+jdbc+springMVC)