LeetCode week 7 : Jump Game II
来源:互联网 发布:格力大数据工程师 编辑:程序博客网 时间:2024/05/18 01:19
题目
地址:
https://leetcode.com/problems/jump-game-ii/description/
类别: Greedy
难度: Hard
描述:
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.
分析
题目要求根据非负数组中的元素进行跳跃,其中数组中的每个元素表示当前位置向后跳跃的最大步数,起点位于数组起始位置,需要求出最佳跳跃方式使得最终跳跃总次数最小,并输出总次数。
解决
思路一
贪心策略:从起点出发往后跳跃时,每次都选择跳到最有潜力的点,即跳到能往后跳最远的点。
代码实现
class Solution {public: int jump(vector<int>& nums) { int current = 0, current_max = nums[0], next_max = 0, next = 0, steps = 0; if(nums.size() == 1) return 0; while(current_max < nums.size()-1) { for(int j = current + 1; j <= current_max && j <= nums.size()-1; j++) { if(nums[j] + j >= next_max) { //更新最有潜力的点 next_max = nums[j] + j; next = j; } } current = next; //跳到该点 current_max = next_max; steps++; } steps++; //退出循环时还差一次跳跃才能到达最后点 return steps; }};
思路二
转化为BFS:如2,3,1,1,4,2,6遍历顺序为2–3,1–1,4–2,6,则最终一共有几层即为跳跃次数。虽然思路不同,但最终代码是与上相似的。
代码实现
class Solution {public: int jump(vector<int>& nums) { int level = 0, current_level_max = nums[0] + 0, next_level_start = 1, next_level_max = 0; if(nums.size() == 1) return 0; while(current_level_max < nums.size() - 1) { for(int next = next_level_start; next <= current_level_max; next++) { if(nums[next] + next >= next_level_max) { next_level_max = nums[next] + next; } } next_level_start = current_level_max; current_level_max = next_level_max; level++; } level++; return level; }};
- LeetCode week 7 : Jump Game II
- [leetcode 55. Jump Game]week 7
- [week 19][Leetcode]Jump Game
- LeetCode week 6 : Jump Game
- 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
- [leetcode] Jump Game II
- LeetCode - Jump Game II
- LeetCode:Jump Game II
- 机器学习SVM算法原理之线性可分情况
- MyEclipse 10 注册码 破解 到期限制
- java环境变量配置
- github上不去--通过修改host解决github上不去的问题
- C#检查foreach判读是否为null的方法
- LeetCode week 7 : Jump Game II
- 三种解析xml的方法
- 跟随页面position漂亮效果浮动插件
- 两步解决win10,win8 环境下 安装svn等一系列msi 2503 2502失败的实用方法
- 宝妈,大学生怎么在家赚钱
- 浅析Java中的final关键字
- 技术文章转载(不定期更新)
- ubuntu下将应用程序快捷方式添加到启动器
- IntelliJ Idea 2017 免费激活方法