力扣练习之跳跃游戏

我爱海鲸 2023-07-13 16:54:20 力扣、中级算法

简介中级算法、动态规划

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvb8zs/

解法一(python):

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

思路:

  1. 从数组的第一个位置开始,记录当前可到达的最远位置为 farthest = 0

  2. 遍历数组中每个位置 i,如果 i 可以到达且跳到的位置 i+nums[i] 更远,则更新 farthest = i+nums[i]

  3. 如果 farthest >= n-1,即最远可以跳到的位置已经超过了数组最后一个位置,那么说明可以到达最后一个位置,返回 true

  4. 如果在遍历完数组后仍然没有满足条件的情况,说明无法到达最后一个位置,返回 false

2023-07-13 start:

解法二(java):

class Solution {
    public boolean canJump(int[] nums) {
        int farthest = 0;
        int len = nums.length;
        for (int i = 0 ; i < len; i++) {
            if (farthest < i) {
                return false;
            }
            farthest = Math.max(farthest,i+nums[i]);
            if (farthest >= len-1) {
                return true;
            }
        }
        return false;
    }
}

思路:同解法一

end

你好:我的2025