leetcode-pp / 91alg-13-daily-check

0 stars 0 forks source link

【Day 67 】2024-06-13 - 55. 跳跃游戏 #68

Open azl397985856 opened 3 weeks ago

azl397985856 commented 3 weeks ago

55. 跳跃游戏

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/jump-game/

前置知识

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个位置。

示例 1:

输入: [2,3,1,1,4] 输出: true 解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。 示例 2:

输入: [3,2,1,0,4] 输出: false 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

smallppgirl commented 3 weeks ago

思路: 贪心法 代码

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

时间复杂 O(n) 空间复杂 O(1)

Martina001 commented 3 weeks ago

思路:只要每次跳到的最大值>=当前索引,就可以继续往后,同时判断是否到达终点;否则就说明无法继续跳,返回false 时间/空间复杂度:O1

private boolean canJump2(int[] nums) {
        int n = nums.length;
        int maxRight = 0;
        for(int i =0;i<n;i++) {
            // 先判断maxRight小于i了没,如果没有才可以继续更新maxRight的值,不可反过来先更新maxRight再判断
            if(i >maxRight){
                return false;
            }
            maxRight = Math.max(maxRight,i+nums[i]);
            if(maxRight >= n - 1) {
                return true;
            }
        }
        return true;
    }
lxy1108 commented 2 weeks ago
class Solution:
    def canJump(self, nums: List[int]) -> bool:
        pos = 0
        for i in range(len(nums)):
            if i<=pos:
                pos = max(pos,i+nums[i])
                if pos>=len(nums)-1:
                    return True
        return False