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

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

算法描述:

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.

Example:

Input: [2,3,1,1,4]Output: 2Explanation: 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.

解题思路:贪心法。每次达到当前最大能够到达的最大值时,步数加一。

int jump(vector
& nums) { if(nums.size()==0) return 0; int curMax = 0; int res = 0; int maxReach= 0; for(int i=0; i < nums.size()-1; i++){ maxReach = max(maxReach, i+nums[i]); if(i == curMax){ res++; curMax = maxReach; } } return res; }

 

转载于:https://www.cnblogs.com/nobodywang/p/10369688.html

你可能感兴趣的文章
微任务、宏任务与Event-Loop
查看>>
PHP代码自动检测(git/svn集成PHP_CodeSniffer)
查看>>
观察者模式(Observer)
查看>>
领域驱动设计实战案例(五):订单上下文POCO模型
查看>>
iOS响应者链彻底掌握
查看>>
css
查看>>
element 源码学习六 —— Carousel 走马灯学习
查看>>
【跃迁之路】【446天】刻意练习系列205(2018.04.27)
查看>>
[经验] 跨域方案
查看>>
通过sqli-labs学习SQL注入(1)
查看>>
【386天】我爱刷题系列145(2018.02.26)
查看>>
Spring Boot 2.0已发布,来聊聊它的新特性。
查看>>
看好还是看衰?8位业界大咖这么看Serverless的2018
查看>>
LUCI用到的一些方法记录
查看>>
reselect的替代者repure
查看>>
NPM酷库:file-type,检测文件类型
查看>>
使用原生JS 或jquery ajax 获取上传图片实时进度
查看>>
简述Hadoop 1.X 系统原理
查看>>
使用 rails/jquery-ujs 来编写非侵入式的 js 模板代码
查看>>
Javascript元编程之Annotation
查看>>