Jump Game II
2016-02-29 11:33
357 查看
题目:
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
思想:
本题可以采用贪心算法的思想,每次尽可能多的jump max distance from one region (old-last,last) to anther (last,curr).
代码:
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.)
思想:
本题可以采用贪心算法的思想,每次尽可能多的jump max distance from one region (old-last,last) to anther (last,curr).
代码:
class Solution { public: int jump(vector<int>& nums) { int len = nums.size(); int start = 0;//每一跳的起始位置 int end = 0;//每一跳的终止位置 int jumps = 0;//跳数 for (int i = 0; i < len; i++) { if (i > end) { end = start; jumps++; } start = max(start, i + nums[i]); } return jumps; } };
相关文章推荐
- VB.NET程序目录下写日志
- muduo库的学习8---TcpServer与TcpClient的基本设计---TcpServer
- 静态分配的顺序表
- 前端页面查看接口快捷键
- c++ const类成员函数
- AXIOM解析XML 详细原理
- hdu 3879 Base Station bzoj 1497 最大获利问题 最大权闭合子图
- 英语总结
- maven之应用总结
- 产品经理反型记 | 解答新人面试中遇到的问题
- muduo库的学习7---TcpServer与TcpClient的基本设计---总论
- Android控件GridView之仿支付宝钱包首页带有分割线的GridView九宫格的完美实现
- redis3.x cluster设计
- Java中的DatagramPacket与DatagramSocket的初步
- 初窥Linux 之 我最常用的20条命令
- 【转】Java ConcurrentModificationException异常原因和解决方法
- 第一个shell编程,输出hello world!
- 无法解析的外部符号
- 函数工厂
- Android全局异常处理(捕获异常,不弹出程序崩溃)