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.

  • 相关阅读:
    Markdown基本语法
    面向对象
    LeetCode739 每日温度
    LeetCode155 最小栈
    LeetCode279 完全平方数
    LeetCode752 打开转盘锁
    LeetCode622 设计循环队列
    LeetCode200 岛屿的个数
    LeetCode61 旋转链表
    LeetCode138 复制带随机指针的链表
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4834075.html
Copyright © 2011-2022 走看看