LeetCode算法题——Jump Game II
来源:互联网 发布:html5 css3 js pdf 编辑:程序博客网 时间:2024/06/10 15:10
题目概述
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.)
分析
这一题的难点在于每一步跳的次数不确定。为了不遗漏情况,我们应当遍历每一个点,利用贪心算法,检查每一个当前位置可以到达的点,选择最远的点,作为本次跳跃的目标点。代码如下:
int jump(vector<int> &nums) { int steps = 0, start = end = 0, maxend = 0; while (end < nums.size()) { steps++; for (int i = start; i <= end; i++) { maxend = max(maxend, nums[i] + i); // 选择出跳跃的点 } start = end + 1; // 从跳跃目标点的下一个点开始下一次循环 end = maxend; // 下一次跳跃最远能到达的点 }}
算法的时间复杂度为O(n),最坏的时候需要完整遍历数组;空间复杂度为O(1)。
总结
此题运用贪心算法,即提前算出下一步的下一步最远能跳到哪里,选择出最大值,决定出下一步跳跃的目标点。
阅读全文
0 0
- LeetCode算法题——Jump Game II
- 数据结构与算法[LeetCode]——Jump Game I II
- leetcode 045 —— Jump Game II
- leetcode——Jump Game II
- LeetCode OJ算法题(四十四):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] 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
- LeetCode-Jump Game II
- 小波分析的理解
- Unity build-in shader 阅读-------HLSLSupporting.cginc
- 笔记-java基础,静态代码块,构造代码块,构造函数。
- LoadBitmap(IDB_BITMAP1)----未定义标志符IDB_BITMAP1
- 计蒜客 17120 Xor
- LeetCode算法题——Jump Game II
- 触发器学习笔记(:new,:old用法)
- 从互联网数据分析师技能掌握要求角度看数据平台架构演变
- 栈+队列--python
- 【GDOI2018模拟9.14】通信
- Redis是可以安装成windows服务-开机自启
- excel中的F1~F12的功能技巧,据说只有3%的职场人员会全部使用!
- js 生成随机数组或者叫做洗牌算法
- hibernate主键生成策略