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

    原题链接在这里:https://leetcode.com/problems/jump-game/

    题目:

    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.

    Determine if you are able to reach the last index.

    Example 1:

    Input: [2,3,1,1,4]
    Output: true
    Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
    

    Example 2:

    Input: [3,2,1,0,4]
    Output: false
    Explanation: You will always arrive at index 3 no matter what. Its maximum
                 jump length is 0, which makes it impossible to reach the last index.

    题解:

    maxJump是需要维护的能跳到的最大值,每当 i 大于maxJump时就说明脱节了.

    maxJump到不了i 不对maxJump做进一步更新。

    loop后面检查maxJump 有没有到 最后一个元素,所示没到,就返回false, 到了就返回 true.

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

    AC Java:

     1 public class Solution {
     2     public boolean canJump(int[] nums) {
     3         if(nums == null || nums.length == 0){
     4             return false;
     5         }
     6         int maxJump = 0;
     7         for(int i = 0; i<nums.length && i<=maxJump; i++){
     8             maxJump = Math.max(maxJump, i+ nums[i]);
     9         }
    10         return maxJump<nums.length-1 ? false:true;
    11     }
    12 }

    跟上Jump Game II.

  • 相关阅读:
    HTTP状态码总结
    spring boot 文件上传
    JQuery Ajax上传文件
    git常用的操作
    git使用ssh clone时报错
    openssl安装
    h5 手机浏览器打开app
    火狐浏览器刷新后表单不重置 (自动填充)
    js Date() 相关
    css中的定位
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4834075.html
Copyright © 2011-2022 走看看