LeetCode45——Jump Game II
来源:互联网 发布:通达信 源码 建仓资金 编辑:程序博客网 时间:2024/06/05 02:23
LeetCode45——Jump Game II
题意:
在一串序列中,每个索引对应的value表示你能跳的最大步数。
你在任何索引处可以跳[1,value]步,求跳到终点处的最小次数。
这题贪心就在于,假设在每个序列处我们都跳它的最大步数。
这里维护两个索引,一个是当前位置curIndex,一个是下一个最大位置nextIndex
现在假设有序列
[2,3,1,1,4]
按照如下步骤:
1.我们的当前位置curIndex = 0,我们从起点出发,我们跳到了最大位置index=2处,其value=1;
2.但是,很明显,如果在起点先跳一步到index=1,value=3处,我们能获取最小跳跃次数。
如何表示呢?
3.回到第1,步,我们需要进行如下迭代,也就是从上一个curIndex=2开始,我们比较nextIndex和index+nums[index]大小,来更新最大的nextIndex。
4.直到curIndex>=endIndex(这里curIndex表示的是更新过的,即用nextIndex替换过的),为了加快迭代速度,由于是求最大值,就不用从上一次比较过的地方开始迭代。
也就是说:不需要增加变量j来记录开始时i的位置。
代码:
class Solution {public:int jump(vector<int>& nums) {int endIndex = nums.size() - 1;int nextIndex = 0;int curIndex = 0;int step = 0;int i = 0;while (i<nums.size()){if (curIndex >= endIndex)break;//int j = i;while (i <= curIndex){nextIndex = max(nextIndex, nums[i] + i);//greedy//j++;i++;}curIndex = nextIndex;step++;}return step;}};
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【贪心】
- leetcode 045 —— Jump Game II
- leetcode——Jump Game II
- Leet Code—Jump Game II
- Algorithms—45.Jump Game II
- Jump Game &Jump Game II
- Jump Game/Jump Game II
- 数据结构与算法[LeetCode]——Jump Game I II
- 经典算法——Jump Game(II)
- 第七周项目2--建立链队算法库
- UI第二天总结
- POM文档简要说明
- 利用switch语句解决问题:成绩等级
- 字符编码
- LeetCode45——Jump Game II
- iOS用户首选项NSUserDefaults浅析
- VS2013常用快捷键
- 第8周、项目5—计数的模式匹配
- Linux内核加载全流程
- ArcEngine CSharp绘制图形经典代码
- 第四周项目3——单链表应用(3)
- ERROR ITMS-90502:"Invalid Bundle. Apps that only contain the arm64 slice must also have 'arm64'
- Android:layout_gravity和android:gravity的区别