您的位置:首页 > 其它

【LeetCode】55. Jump Game

2017-01-08 10:30 519 查看
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
.

Difficulty: Medium

贪心算法,思路是每一步确定能走的最大步数,如果中途出现最大步数为0的情况,则不能走到终点,如果中途出现最大步数大于当时的下标距离终点的距离,则可以到达

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