leetcode - Jump Game II
来源:互联网 发布:手机刷软件 编辑:程序博客网 时间:2024/06/10 05:02
题目:
Jump Game II
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.)
分析:
贪婪算法,每跳一步都要求“利益最大化”(即每一步都要跳到能延伸最远的那个下标)。
class Solution {public: int jump(vector<int>& nums) { if(nums.size()<=1) return nums.size()==1?0:-1; if(nums[0]==0) return -1; int count=0,right=nums[0];//right是能跳到最右边的下标 for(int i=0;i<nums.size();) { ++count;//肯定要跳一步 if(right>=nums.size()-1)//到达终点,结束 return count; int tmp=0,index=-1; for(int j=i+1;j<=right;++j)//找到能跳最远的那个下标 { if(tmp<j+nums[j]) { tmp=j+nums[j]; index=j; } } if(tmp<=right)//无法超越上一步,则跳不到终点 return -1; else { right=tmp; i=index;//此行代码确定这一轮循环跳到哪个下标 } } return -1; }};
0 0
- 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
- LeetCode | Jump Game II
- 【Leetcode】Jump Game II
- LeetCode Jump Game II
- [LeetCode] Jump Game II
- Poj 1860 Currency Exchange(贝尔曼福特,最长路)
- JUnit4执行cases背后的故事(1)---JUnitCore源码分析
- [华为机试练习题]4.简单密码破解
- HDU 1213
- jetty运行项目
- leetcode - Jump Game II
- Java基础:泛型及其擦除性、不可协变性
- CC2530_温湿度_串口通信
- 一个用 C 语言写的迷你版 2048 游戏,只有 500个字符
- SQL注入的攻击与防御(简单篇)
- ubuntu苹果主题
- 2015个人书单
- The-Swift-2.0-Programming-Language-playground
- C++标准异常类