45. Jump Game II
来源:互联网 发布:西语考试知乎 编辑:程序博客网 时间:2024/05/16 10:13
45. Jump Game II
题目描述: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
. (Jump1
step from index 0 to 1, then3
steps to the last index.)Note:
You can assume that you can always reach the last index.题目含义:给定一个非负数组,初始化在第一个位置,每个元素代表最大能到的位置,找到到达末尾位置的最小跳数。
思路:贪心算法。
代码
package Array;/*** @Author OovEver* @Date 2017/11/29 16:38*/public class LeetCode45 { public static int jump(int[] nums) { int ret = 0;//当前跳数 int last = 0;//上一跳可达最远距离 int cur = 0;//当前一跳可达最远距 for (int i = 0; i < nums.length; ++i) { //无法向前继跳直接返回 if(i>cur){ //有可能无论怎么跳,都不能到达终点或者越过终点,比如[3,2,1,0,4]。 return -1; } //需要进行下次跳跃,则更新last和当执行的跳数ret if (i > last) { last = cur; ++ret; } //记录当前可达的最远点 cur = Math.max(cur, i+nums[i]); } return ret; } public static void main(String[] args) { int[] nums = {2, 3, 1, 1, 4}; System.out.println(jump(nums)); }}
阅读全文
0 0
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 面向文档的开源NoSQL数据库大盘点
- 默认路由添加和删除
- Codeforce 893A Chess For Three (模拟)
- 7.6求阶乘总值
- 基于UDP的Java Socket编程基础
- 45. Jump Game II
- Red and Black
- 程序员 帅!
- 求连续子数组最大和
- 基于邻接矩阵的深度优先搜索遍历
- Java并发编程基础(一)
- Cadence Pspice添加外部白噪声
- JDBC注册多个驱动
- 二叉树遍历