您的位置:首页 > 其它

LeetCode Jump Game II

2015-09-24 03:52 316 查看
原题链接在这里: https://leetcode.com/problems/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.)

题解:

这是的Jump Game进阶版题目。求能跳到最后一个元素的最小步数。

采用了Jump Game中的Method 2. maxJump是维护的当前能跳到的最大位置,maxReach是指从之前的点能reach到得最远位置。

当i 大于之前点能碰到的最大位置时,就需要跳一步,并把maxReach更新为maxJump.

最后返回若是maxJump能到最后一个元素,就返回step, 若是到不了,就说明根本走不到最后一步,返回0.

Time Complexity: O(n). Space: O(1).

AC Java:

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