zoukankan      html  css  js  c++  java
  • LeetCode 45. Jump Game II

    原题链接在这里: https://leetcode.com/problems/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.

    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.

    题解:

    Have max initialized as 0. Up to max, keep updating reach range, when we hit max, we need to jump.

    And assign the new range to max, if max is already beyong nums.length, return steps.

    Time Complexity: O(n). Space: O(1).

    AC Java:

     1 class Solution {
     2     public int jump(int[] nums) {
     3         if(nums == null || nums.length < 2){
     4             return 0;
     5         }
     6         
     7         int max = 0;
     8         int reach = 0;
     9         int res = 0;
    10         for(int i = 0; i<nums.length; i++){
    11             reach = Math.max(reach, i + nums[i]);
    12             if(i == max){
    13                 res++;
    14                 max = reach;
    15                 if(max >= nums.length - 1){
    16                     return res;
    17                 }
    18             }
    19         }
    20         
    21         return -1;
    22     }
    23 }

    类似Jump Game.

  • 相关阅读:
    #2019090700004
    51nod 1191-贪心+并查集
    hdu 5015-矩阵快速幂
    树形DP—依赖背包模板
    HDU 1074—压缩DP
    动态绑定的开销
    动态绑定
    静态绑定(前期绑定)
    继承的一些优点
    多态置换原则初始化基类对象
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4834079.html
Copyright © 2011-2022 走看看