Skip to content

[LeetCode] 55. 跳跃游戏 #84

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Sep 7, 2019 · 0 comments
Open

[LeetCode] 55. 跳跃游戏 #84

Animenzzzz opened this issue Sep 7, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个位置。

示例 1:

输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。

示例 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

解题思路:使用贪心算法,i+nums[i]为当前位置下能跳到的最远距离,跳出循环的两个条件:1.i>reach,说明不管怎么跳,已经无法跳到i这个位置 2.能达到的最远距离超过了数组长度,即能达到

C++解题:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int reach = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            if(i > reach || reach >= nums.size()-1) break;
            reach = max(i+nums[i],reach);
        }
        return reach >= nums.size()-1? true:false;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant