55. 跳跃游戏(Jump Game)

题解

贪心算法

  1. 定义目前达到的最远位置m a x _ b o u n d = 0 max\_bound=0max_bound=0,和上一步到达的边界e n d = 0 end=0end=0
  2. 遍历数组,遍历范围[ 0 , n ) [0,n)[0,n)
    • 所能达到的最远位置m a x _ b o u n d = m a x ( m a x _ b o u n d , n u m s [ i ] + i ) max\_bound=max(max\_bound,nums[i]+i)max_bound=max(max_bound,nums[i]+i),表示上一最远位置和当前索引i ii和索引i ii上的步数之和中的较大者。
    • 如果索引i ii到达了上一步的边界e n d endend,即i = = e n d i==endi==end,则:
      • 更新边界e n d endend,令e n d endend等于新的最远边界m a x _ b o u n d max\_boundmax_bound,即e n d = m a x b o u n d end=max_boundend=maxbound
      • 判断可到达边界是否大于等于n − 1 n-1n1,若满足,则返回T r u e TrueTrue
  3. 返回F a l s e FalseFalse
    **注意!**数组遍历范围为[ 0 , n ) [0,n)[0,n),和45.跳跃游戏II不同的是,这里只需判断能否到达,而不需精确的步数。

复杂度分析

  • 时间复杂度:O ( n ) O\left(n\right)O(n)
  • 空间复杂度:O ( 1 ) O(1)O(1)

Python

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        max_bound=0
        n=len(nums)
        end=0
        for i in range(n):
            max_bound=max(max_bound,nums[i]+i)
            if(i==end):
                end=max_bound
            if(end>=n-1):
                return True
        return False

Java(待完成)

从后向前

  1. 定义索引l a s t _ i n d e x = n − 1 last\_index=n-1last_index=n1

  2. 遍历范围[ n − 1 , 0 ] [n-1,0][n1,0],倒序遍历:

    • 若当前位置可到达的边界大于等于l a s t _ i n d e x last\_indexlast_index,说明可将l a s t _ i n d e x last\_indexlast_index更新到当前位置,即l a s t _ i n d e x = i last\_index=ilast_index=i
  3. l a s t _ i n d e x = = 0 last\_index==0last_index==0,说明从0 00处可以到达n − 1 n-1n1处,返回T r u e TrueTrue,否则返回F a l s e FalseFalse

复杂度分析

  • 时间复杂度:O ( n ) O\left(n\right)O(n)
  • 空间复杂度:O ( 1 ) O(1)O(1)

Python

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        lastindex=len(nums)-1
        for i in range(len(nums)-1,-1,-1):
            if(i+nums[i]>=lastindex):
                lastindex=i
        return lastindex==0

Java(待完成)


版权声明:本文为zhushaojiecumt原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。