0045. Jump Game II (H)

Jump Game II (H)

题目

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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.


题意

给定一个数组,每个数字元素代表以当前下标为起点,能够向右走的步数,返回该数组能从第一个元素开始走到最后一个元素所需要的最小步数。

思路

55. Jump Game 基础上,对方法做出修改:

第一种方法代码结合图更清晰:

贪心:变量lastPos初值为nums.length - 1,从右向左遍历,对于每一个lastPos,找到它左侧最左边一个满足 left + nums[left] >= lastPos 的值left,步数加1,并更新 lastPos = left,重复上述步骤直到 lastPost = 0。


代码实现

Java

迭代

class Solution {
    public int jump(int[] nums) {
        int count = 0;
        int preLast = 0;			// 上一步最远能到达的位置
        int last = 0;				// 下一步最远能到达的位置

        for (int i = 0; i < nums.length; i++) {
            // 当上一步能到达的位置全部走完后,要到更远的位置需要多迈一步
            if (i > preLast) {
                count++;
                preLast = last;
            }
            last = Math.max(last, i + nums[i]);		// 更新下一步最远能到达的位置
        }

        return count;
    }
}

贪心

class Solution {
    public int jump(int[] nums) {
        int count = 0;
        int lastPos = nums.length - 1;
        int left = lastPos;
        
        while (lastPos != 0) {
            // 每次找到最左边一个能够到达lastPos的位置
            for (int i = lastPos - 1; i >= 0; i--) {
                if (i + nums[i] >= lastPos) {
                    left = i;
                }
            }
            count++;
            lastPos = left;
        }
        
        return count;
    }
}

JavaScript

迭代

/**
 * @param {number[]} nums
 * @return {number}
 */
var jump = function (nums) {
  let step = 0
  let start = 0
  let end = 0

  while (end < nums.length - 1) {
    step++
    let max = end
    for (let i = start; i <= end; i++) {
      max = Math.min(Math.max(max, nums[i] + i), nums.length - 1)
    }
    start = end + 1
    end = max
  }

  return step
}

贪心

/**
 * @param {number[]} nums
 * @return {number}
 */
var jump = function (nums) {
  let step = 0
  let pos = nums.length - 1

  while (pos !== 0) {
    let i = 0
    while (nums[i] + i < pos) {
      i++
    }
    pos = i
    step++
  }

  return step
}
posted @ 2020-06-30 01:45  墨云黑  阅读(132)  评论(0编辑  收藏  举报