博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】Jump Game I, II 跳跃游戏一和二
阅读量:6872 次
发布时间:2019-06-26

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

题目:

Jump Game I:

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.

Determine if you are able to reach the last index.

For example:

A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

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. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Java代码例如以下:

public class Jump_Game {	public static void main(String[] args) {		int[] A = { 2, 3, 1, 1, 4 };		int[] B = { 3, 2, 1, 0, 4 };		System.out.println(canJump(A));		System.out.println(canJump(B));	}	public static boolean canJump(int[] A) {		boolean[] can = new boolean[A.length];		can[0] = true;		for (int i = 1; i < A.length; i++) {			for (int j = 0; j < i; j++) {				if (can[j] && j + A[j] >= i) {					can[i] = true;					break;				}			}		}		return can[A.length - 1];	}}

public class jump_game_2 {	public static void main(String[] args) {        	int[] A = { 2, 3, 1, 1, 4 };		int[] B = { 3, 2, 1, 0, 4 };		System.out.println(jump(A));		System.out.println(jump(B));	}	public static int jump(int[] A) {		int[] steps = new int[A.length];		steps[0] = 0;		for (int i = 1; i < A.length; i++) {			steps[i] = Integer.MAX_VALUE;			for (int j = 0; j < i; j++) {				if (steps[j] != Integer.MAX_VALUE && j + A[j] >= i) {					steps[i] = steps[j] + 1;					break;				}			}		}		return steps[A.length - 1];	}}

转载地址:http://bbpfl.baihongyu.com/

你可能感兴趣的文章
[leetcode]Rotate List @ Python
查看>>
Asp.Net转换Html加号显示为空格的字符!(自已备用)
查看>>
C#-Mdi多文档窗体及其子窗体的排列 ---ShinePans
查看>>
hive 权限:Authorization failed:No privilege 'Create' found for outputs .
查看>>
Unit Test单元测试时如何模拟HttpContext
查看>>
高级PHP应用程序漏洞审核技术
查看>>
菜鸟教程之工具使用(一)——Git的基本使用
查看>>
如何处理数组越界而不会让程序崩溃?
查看>>
比较排序算法
查看>>
Quartz.NET作业调度框架详解
查看>>
Android开发之Intent跳转到系统应用中的拨号界面、联系人界面、短信界面
查看>>
C++内存未释放的情况
查看>>
UNION并集运算
查看>>
如何关掉UAC?
查看>>
请保护我们的地球
查看>>
jenkins 神奇变量
查看>>
Linux 输出文件列数,拼接文件
查看>>
迷你MVVM框架 avalonjs 学习教程2、模块化、ViewModel、作用域
查看>>
atitit.避免NullPointerException 总结and 最佳实践 o99
查看>>
uGUI练习(七) Drag And Drop
查看>>