xinyu04

导航

LeetCode 55 Jump Game 贪心

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

Solution

每次计算最远能走到的位置,时间复杂度\(O(n)\)

点击查看代码
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int n = nums.size();
        if(n==1)return true;
        else{
            int max_reach=0;
            for(int i=0;i<n;i++){
                if(i>max_reach)return false;
                max_reach = max(max_reach,i+nums[i]);
            }
            return true;
        }
        
    }
};

posted on 2022-05-01 03:01  Blackzxy  阅读(18)  评论(0编辑  收藏  举报