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.

  • 相关阅读:
    各种编译器
    C99特性
    动态内存分配
    MDK C++编程说明
    C++类的大小计算
    WPF DataGrid添加编号列
    WPF实现打印用户界面功能
    WPF DataGrid 导出Excel
    知识点总结
    Winfrom控件使用
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4834079.html
Copyright © 2011-2022 走看看