C/C++教程

LeetCode 55 Jump Game 贪心

本文主要是介绍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;
        }
        
    }
};
这篇关于LeetCode 55 Jump Game 贪心的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!