您的位置:首页 > 其它

leetcode--Jump Game

2017-05-02 21:16 302 查看
Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:

A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

解题思路:由于每层最多可以跳 A[i] 步,也可以跳 0 或 1 步,因此如果能到达最高层,则说明每一层都可以到达。有了这个条件,说明可以用贪心法。思路:正向,从 0 出发,一层一层网上跳,看最后能不能超过最高层,能超过,说明能到达,否则不能到达。

代码:

class Solution {
public:
bool canJump(vector<int>& nums) {
int reach = 1; // 最右能跳到哪里
for (int i = 0; i < reach && reach < nums.size(); ++i)
reach = max(reach, i + 1 + nums[i]);
return reach >= nums.size();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: