您的位置:首页 > 编程语言 > Java开发

Leet Code 45 Jump Game II - 跳跃游戏 - Java

2016-06-22 00:00 489 查看
摘要: Leet Code 45 Jump Game II - 跳跃游戏 - Java

问题原始链接 https://leetcode.com/problems/jump-game-ii

给定一个非负整数数组,你的初始位置为数组的第一个索引。

数组中的每个元素表示你在那个位置的最大跳跃长度。

例如,给定数组 A = [2,3,1,14],到达最后一个索引的跳跃次数为2。(从索引0跳1步到索引1,然后跳3步到最后一个索引。

注意:

你可以假设总是可以到达最后一个索引。

第一种方法,假设数组为a,数组长度为n,申请一个数组step
,step[i]表示跳到i位置需要的最少步数,step[0]=1。从左往右扫描数组,在位置i时更新step[i+1..i+a[i]],step[j]=min(step[j], step[i]+1)。

这种方法性能太差。LeetCode超时。

public class Solution {
public static int jump(int[] nums) {
if (nums == null || nums.length <= 1) {
return 0;
}
int[] step = new int[nums.length];
for (int i = 0; i < nums.length - 1; i++) {
int end = i + nums[i];
if (end >= nums.length - 1) {
return step[i] + 1;
}
for (int j = i + 1; j <= i + nums[i] && j < nums.length; j++) {
step[j] = step[j] == 0 ? step[i] + 1 : Math.min(step[j], step[i] + 1);
}
}
return step[nums.length - 1];
}
}

第二种方法

整型变量jump,表示目前跳了多少次。整型变量cur,表示如果只能跳jump次,能达到的最远的位置。整型变量next,表示如果再多跳一次,能达到的最远的位置。

public class Solution {
public static int jump(int[] nums) {
if (nums == null || nums.length <= 1) {
return 0;
}
int jump = 0;
int cur = 0;
int next = 0;
for (int i = 0; i < nums.length; i++) {
if (cur < i) {
jump++;
cur = next;
}
next = Math.max(next, i + nums[i]);
}
return jump;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息