您的位置:首页 > 其它

LeetCode 55. Jump Game(跳跃游戏Ⅰ)

2018-03-22 15:36 411 查看
题目描述:
    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,大小为n。A[i]表示从i位置出发的最大跳跃步数。判断是否能从0点出发,到达n - 1点。
    思路:这道题时LeetCode 45的进化版本。思路都是贪心算法,具体细节这里不再详细复述,主要讲跟LeetCode 45的区别:对于每一个位置i,我们用pre表示i之前能够达到的最远位置,cur表示包含从i出发的情况,此时能够到达的最远位置。① 如果i > pre,则说明当前i位置已经超出了前一步的最远跳跃点,无法完成衔接,因此无法到达n - 1点;② i的取值范围考虑为0→n - 1而不是0→n - 2,因为最后一步也要判断,之前的最大跳跃点能否到达。
    时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
// Exceptional Case:
if(n <= 1){
return true;
}
int preMaxEnd = 0, curMaxEnd = 0;
// for(int i = 0; i <= n - 2; i++){ will cause an error!
for(int i = 0; i <= n - 1; i++){
if(i > preMaxEnd){
return false;
}
curMaxEnd = max(curMaxEnd, i + nums[i]);
if(i == preMaxEnd){
preMaxEnd = curMaxEnd;
}
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C LeetCode Greedy