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 }
  • 相关阅读:
    C 语言定义
    一次系统磁盘异常使用100%的处理
    supervisord 安装、配置体验
    uva 211(dfs)
    poj1651
    有一种感动叫ACM(记WJMZBMR在成都赛区开幕式上的讲话)
    nyoj-746
    Codeforces Round #308 (Div. 2)----C. Vanya and Scales
    long long 与 _int64
    石子归并问题(nyoj737)
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4859913.html
Copyright © 2011-2022 走看看