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 }
  • 相关阅读:
    软件测试课堂练习
    JSP第一次作业
    安卓第六次作业
    安卓第五次作业
    第四次安卓作业
    JSP第四周
    软件测试课堂练习3.4
    Android数据库表
    Android购物菜单
    Android增删改查
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4859913.html
Copyright © 2011-2022 走看看