(LeetCode 面试经典 150 题 ) 55. 跳跃游戏 (贪心)

题目:55. 跳跃游戏

(LeetCode 面试经典 150 题 ) 55. 跳跃游戏 (贪心)_第1张图片
思路:贪心,维护可达的最远距离last。时间复杂度0(n)。

C++版本:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int last=0;
        for(int i=0;i<nums.size();i++){
            if(last<i) return false;
            last=max(last,nums[i]+i);
        }
        return true;
    }
};

JAVA版本:

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

Go版本:

func canJump(nums []int) bool {
    last:=0
    for i:=0;i<len(nums);i++ {
        if last<i {
            return false
        }
        last=max(last,i+nums[i])
    }
    return true
}

你可能感兴趣的:(LeetCode,LeetCode,面试经典,150,题,C++,JAVA,Go版本,leetcode,面试,游戏,c++,java,go)