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.

  • 相关阅读:
    Vue学习路线
    国庆游
    Axure RP 9 Beta 开放下载(更新激活密钥和汉化包)
    python虚拟环境
    异步任务神器 Celery-入门
    pymysql操作mysql
    安装 RabbitMQ
    GIT工作流
    flask入门与发送邮件与QQ邮箱
    Mysql第一周
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4834075.html
Copyright © 2011-2022 走看看