您的位置:首页 > 编程语言 > Go语言

[LeetCode] Algorithms-55. Jump Game

2018-01-11 02:26 477 查看

描述:

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.

思路:

这个思路是参考leetcode后面的提供的解决方法Approach#4的思路,即先思考什么情况是可以到达的,不过那道题是使用的逆向思维的方法,个人感觉不是很好理解,于是在参考这个方法后整理出正面思维使用贪心算法的解题思路:

思路是这样的:

开一个变量reach记录整个数组中的 “每个元素能到达的最远位置” (这句话比较绕,加个引号应该更好理解)的最大值,如果说当便利当遍历完整个数组,得到的下标值大于数组的最大的下标(也就是最后一个元素的下标),那这种情况就返回true,如果不行的话就返回false。

怎么样,很形象是吧。

数组中一个元素能到达的最远距离等于 “当前元素的下标值加上元素本身的值” ,贪心算法体现的地方,就是用reach变量记录整个数组能到达的最远距离。

代码:

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