zoukankan      html  css  js  c++  java
  • Jump Game II 解答

    Question

    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.)

    Solution

    This problem can be transformed into "Given step n, what is the largest distance that you can reach?"

    Beside maintaining an array to record farest reachable position, we need also know how farest current jump can reach.

    Example

     1 public class Solution {
     2     public int jump(int[] nums) {
     3         if (nums == null || nums.length < 1)
     4             return -1;
     5         int length = nums.length;
     6         // Three variables
     7         // maxReach: max reachable position for current index and previous indexes
     8         // maxJumpReach: max position that can be reachable by n jump steps
     9         // jump: jump steps
    10         int maxReach = nums[0];
    11         int maxJumpReach = 0;
    12         int jump = 0;
    13         for (int i = 0; i < length && maxJumpReach <= (length - 1); i++) {
    14             if (i > maxJumpReach) {
    15                 jump++;
    16                 maxJumpReach = maxReach;
    17             }
    18             maxReach = Math.max(maxReach, i + nums[i]);
    19         }
    20         return jump;
    21     }
    22 }
  • 相关阅读:
    Codeforces 1154C Gourmet Cat
    copy 浅拷贝 深拷贝
    sort and sorted 区别
    python第四天
    python入门第三天_练习
    可持久化trie
    bzoj 3261 最大异或和【可持久化trie】
    bzoj 2716 [Violet 3]天使玩偶 【CDQ分治】
    bzoj 1176 [Balkan2007]Mokia 【CDQ分治】
    CDQ分治
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4859913.html
Copyright © 2011-2022 走看看