leetcode45. Jump Game II

来源:互联网 发布:windows怎么取消共享 编辑:程序博客网 时间:2024/06/04 19:37

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. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)Note:You can assume that you can always reach the last index.

解法一

step[i]表示跳到这步最少需要几步。step[i]每次取 step[i] = Math.min(step[i], step[j] + 1),j为小于等于i的位置。
时间复杂度为O(n),超时。

public class Solution {    public int jump(int[] nums) {        if (nums == null || nums.length == 0) {            return 0;        }        // state        int[] step = new int[nums.length];        // initialize        step[0] = 0;        for (int i = 1; i < nums.length; i++) {            step[i] = Integer.MAX_VALUE;        }        for (int i = 0; i < nums.length; i++) {            for (int j = 0; j < i; j++) {                if (step[j] != Integer.MAX_VALUE && j + nums[j] >= i) {                    step[i] = Math.min(step[i], step[j] + 1);                }            }        }        return step[nums.length - 1];    }}

解法二

贪心算法:每一次跳跃都有一个范围,每次记录最远到达的位置farthest。下一次的start为end+1,end=farest,即为上一跳所能跳到的范围。然后再循环范围内的位置,找到最远的位置。直到某一跳达到最后一个位置停止,每一跳+1。

public class Solution {    public int jump(int[] nums) {        if (nums == null || nums.length == 0) {            return -1;        }        int start = 0, end = 0, jumps = 0;        while (end < nums.length - 1) {            jumps++;            int farthest = end;            for (int i = start; i <= end; i++) {                if (nums[i] + i > farthest) {                    farthest = nums[i] + i;                }            }            start = end + 1;            end = farthest;        }        return jumps;    }}

这里写图片描述

0 0
原创粉丝点击