难度:中等
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4] 输出: true 解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4] 输出: false 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
题目解析:
分析一下,贪心算法吧,每次跳最大的位置看能不能跳到最后一个位置。
参考代码:
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <deque>
#include <stack>
#include <algorithm>
#include <map>
using namespace std;
class Solution {
public:
bool canJump(vector<int>& nums) {
if (nums.empty())
return true;
int max = 0; //用于记录最大的位置
int end = nums[0];//先走到当前的最大位置
for (int i = 0; i <= end; i++)
{
//更新最大位置
if (i + nums[i] > max)
max = i + nums[i];
//最大位置超过最后一个位置,说明肯定能到
if (max >= nums.size() - 1)
return true;
//走到当前位置时,更新一下下一个要走的点
if (i == end && max > end)
end = max;
}
return false;
}
};
int main(void)
{
Solution my_class;
vector<int> matrix = { 3, 2, 1, 0, 4 };
vector<int> res;
if (my_class.canJump(matrix))
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
system("pause");
return 0;
}