leetcode(45):Jump Game II
来源:互联网 发布:jquery查询前清空数据 编辑:程序博客网 时间:2024/05/16 12:12
原题:
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.)
分析:此题是Jump Game的升级,需要求出从数组第一个元素到达最后一个元素的所需的最小的步数。
Java实现:时间复杂度为O(n)
public class Solution { public int jump(int[] nums) { int ret=0;//记录当前为止的步数 int last = 0;//记录上一跳能到达的最远距离,用数组下标表示 int cur = 0;//记录当前一跳能到达的最远距离 for (int i = 0; i < nums.length; i++) { if(i>cur) {//当前一条不能到达,即最后一个元素不可达,返回-1 return -1; } if(i>last){//上一跳还不能到达当前位置,需要再跳一次,ret+1,并更新last值 ret++; last=cur; } cur =Math.max(cur, i+nums[i]);//更新当前跳数 } return ret; }}
0 0
- [leetcode 45] Jump Game II
- LeetCode(45) Jump Game II
- [LeetCode 45]Jump Game II
- leetcode || 45、 Jump Game II
- leetcode 45:Jump Game II
- 【LeetCode】45:Jump Game II
- leetcode 45: Jump Game II
- LeetCode-45 Jump Game II
- Leetcode#45||Jump Game II
- leetcode-45 Jump Game II
- Leetcode #45 Jump Game II
- leetcode 45:Jump Game II
- LeetCode 45 - Jump Game II
- 【LeetCode-45】Jump Game II
- LeetCode 45 Jump Game II
- leetcode(45):Jump Game II
- Leetcode 45 Jump Game II
- Leetcode (45) Jump Game II
- iOS和Android需要保持体验一致吗?
- ObjectMapper将json字符串转换成泛型List/map
- linux升级gcc支持c++11
- [解决] storm启动异常:org.apache.thrift7.transport.TTransportException
- Operate XML
- leetcode(45):Jump Game II
- 常用docker命令
- AndroidStudio怎样导入library项目开源库
- hibernate 多对多
- FreeCMS视频教程 还原数据库 oracle
- git 覆盖分支
- word-wrap word-break 张鑫旭博客
- webdriver 关于元素的常用操作 python版本
- Application(ServletContext)在负载均衡上面的问题