0
点赞
收藏
分享

微信扫一扫

LeetCode 面试经典150题 55.跳跃游戏

止止_8fc8 03-18 19:00 阅读 2

题目

给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false 。

思路:贪心

代码

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

性能:时间复杂度O(n)  空间复杂度O(1)

举报

相关推荐

0 条评论