leetcode - Jump Game II
2015-06-29 00:00
405 查看
题目:
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 =
The minimum number of jumps to reach the last index is
from index 0 to 1, then
分析:
贪婪算法,每跳一步都要求“利益最大化”(即每一步都要跳到能延伸最远的那个下标)。
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
1step
from index 0 to 1, then
3steps 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; } };
相关文章推荐
- CC2530_温湿度_串口通信
- [Swust OJ 402]--皇宫看守(树形dp)
- perl grep 和 map 简单用法
- IO - 同步,异步,阻塞,非阻塞 (亡羊补牢篇)
- 美团酒店Node全栈开发实践
- mysql 常用命令
- 硅谷的实习生们:多数人青睐谷歌
- Maven 中央库 配置
- window.onload和$(function(){})的区别
- Javascript闭包(Closure)
- VO , PO , BO , QO , DAO , POJO
- 易宝典文章——玩转Office 365中的Exchange Online服务 之十 怎样在Exchange Online中配置邮件转发
- cas
- 简明 Git 命令速查表(中文版)
- Linux常用的shell命令
- Docker简明教程
- Nginx 重写规则指南
- PC硬件的那些权威认证
- 研究国内软件加密狗的集成与使用
- PHP_数组常用处理函数