leetcode:Jump Game II 【Java】
2016-03-05 23:04
513 查看
一、问题描述
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 =
The minimum number of jumps to reach the last index is
from index 0 to 1, then
Note:
You can assume that you can always reach the last index.
二、问题分析
利用贪心法,尝试每步都跳到最远。
三、算法代码
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
1step
from index 0 to 1, then
3steps to the last index.)
Note:
You can assume that you can always reach the last index.
二、问题分析
利用贪心法,尝试每步都跳到最远。
三、算法代码
public class Solution { public int jump(int[] nums) { //贪心法 //当只有一阶台阶时,不需要跳,所以所需步数为0 if(nums.length == 1){ return 0; } int step = 0;//当前已经跳的步数 int left = 0; int right = 0;//[left, right]为当前可以跳到的台阶区域 while(left <= right){ //尝试从每一层跳到最远 step++; int old_right = right; for(int i = left; i <= old_right; i++){//从当前可以跳到的区域中再次起跳,看能否到达最后的台阶 int new_right = i + nums[i]; if(new_right >= nums.length - 1){ return step; } if(new_right > right){ right = new_right; } } //当前可以跳到的区域已经搜索完毕,构造下一个起跳区域的起始台阶 left = old_right + 1; } return 0; } }
相关文章推荐
- Java关键字介绍之this与super
- 局部更新 java web 的文件
- java反射和静态代理模式
- java编译命令
- 打印1到最大的n位数 Java
- Quartz定时任务,Quartz Spring定时任务,spring多个定时任务Quartz配置,示例,详解
- leetcode:Single Number II 【Java】
- JavaBean和Servlet的区别
- Android开发搭环境步骤, ADT, JDK, SDK, NDK, Eclipse, CDT
- 学习JAVA环境搭建之下载安装MyEclipse 6.5
- Java内存区域,内存溢出,内存泄漏
- Android开发问题记录(二)——Eclipse不显示Android SDK&AVD Manager
- eclipse 和 android studio 快捷键对比收藏了
- 20145219 《Java程序设计》第01周学习总结
- 简单的SpringMVC+Mybatis整合
- 几种基本排序的java实现
- Java笔记---易混淆的概念(二:线程、进程、任务)
- 《Java程序设计》第一周学习总结
- struts2 拦截器
- LeetCode : Longest Common Prefix [java]