博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode_Jump Game II
阅读量:5337 次
发布时间:2019-06-15

本文共 1434 字,大约阅读时间需要 4 分钟。

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.)

  Greedy:  keep the current maximum reach distance, and the number of steps to reach this current maximum distances, and keep another variable to record the next maximum reachable distance, which cost the current steps plus 1. The key idea behind is that, all the positions before the maximum reachable distance would be able to be reached! Then we linear scan the array to keep updating the current maximum and the next maximum as well as the number of steps. We can achieve the linear time algorithm

class Solution {public:    int jump(int A[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int steps = 0;        int currMax = 0;        int nextMax = 0;        for(int i = 0; i< n; i++)        {           if(i > currMax)          {            currMax = nextMax;            steps++;          }                    nextMax = nextMax > i+A[i] ? nextMax : i+A[i] ;                 }            return steps ;    }};

 

 

转载于:https://www.cnblogs.com/graph/p/3210226.html

你可能感兴趣的文章
【Crash Course Psychology】2. Research & Experimentation笔记
查看>>
关于 linux 的 limit 的设置
查看>>
MTK笔记
查看>>
【题解】 bzoj1597: [Usaco2008 Mar]土地购买 (动态规划+斜率优化)
查看>>
fat32转ntfs ,Win7系统提示对于目标文件系统文件过大解决教程
查看>>
shell cat 合并文件,合并数据库sql文件
查看>>
python全栈 计算机硬件管理 —— 硬件
查看>>
Delphi7编译的程序自动中Win32.Induc.a病毒的解决办法
查看>>
egret3D与2D混合开发,画布尺寸不一致的问题
查看>>
struts1和struts2的区别
查看>>
Redis常用命令
查看>>
微软职位内部推荐-Sr. SE - Office incubation
查看>>
C#类与结构体究竟谁快——各种函数调用模式速度评测
查看>>
我到底要选择一种什么样的生活方式,度过这一辈子呢:人生自由与职业发展方向(下)...
查看>>
poj 题目分类
查看>>
windows 安装yaml支持和pytest支持等
查看>>
读书笔记:季羡林关于如何做研究学问的心得
查看>>
面向对象的优点
查看>>
套接口和I/O通信
查看>>
阿里巴巴面试之利用两个int值实现读写锁
查看>>