LeetCode——045
2016-04-17 16:15
155 查看
/*
45. Jump Game II My Submissions QuestionEditorial Solution
Total Accepted: 62218 Total Submissions: 246687 Difficulty: 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.
Subscribe to see which companies asked this question
*/
/*
解题思路:
此题的核心方法还是利用动态规划Dynamic Programming的思想来解,我们需要两个变量cur和pre分别来保存当前的能到达的最远位置和之前能到达的最远位置,只要cur未达到最后一个位置则循环继续,pre记录cur的值,如果当前位置i小于等于pre,则更新cur然后i自增1。更新cur的方法是比较当前的cur和i + A[i]之中的较大值,等i循环到pre的值时,跳跃的步数加一,如果题目中未说明是否能到达末尾,我们还可以判断此时pre和cur是否相等,如果相等说明cur没有更新,即无法到达末尾位置,返回-1,代码如下:
*/
class Solution { public: int jump(vector<int>& nums) { int n=nums.size(); int res=0,i=0,cur=0; while(cur<n-1){ //记录上次的最远点 int pre=cur; //遍历i~pre之间,找一个能达到最远的位置 while(i<=pre){ cur=max(cur,i+nums[i]); ++i; } ++res; //比较最远点是否发生变化 if(pre==cur)return -1; } return res; } };
相关文章推荐
- java之FileReader与FileWriter
- hdu-5667 Sequence(矩阵快速幂+费马小定理+快速幂)
- 缓存
- 字符串编辑距离(Levenshtein距离)算法
- [LeetCode] 92. Reverse Linked List II
- 命名管道(FIFO)的实现
- FMDB使用基本方法
- 整理下最近在做的android5.0的代码,留用
- 模拟退火 hdu3932
- 本地测试接口代码
- 通过移位把十进制转换成二进制的一个尝试
- opencv基础
- CSS中position属性 (absolute,relative,static,fixed)
- JavaScript Ajax封装 类似jQuery Ajax
- 学习笔记--DOCTYPE
- HDU 5667 Sequence
- Boltzmann Machine 入门(1)
- CSMA/CA与CSMA/CD的区别
- pyton 串口操作
- 【机器学习】QQ-plot深入理解与实现