Descrition:
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.
注:本系列题目均在本地VS2015上运行通过;
题目分析:可以每次贪心的在当下位置记录能reach到达的最大距离,然后在i
//
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
bool jumpgame(const vector<int>& nums) {
if (nums.size() == 0) return false;
if (nums.size() == 1) return true;
int reach = 1;
for (int i = 0; i < reach && reach < nums.size();++i) {
reach = max(reach,i +1+nums[i]);
}
return reach >= nums.size();
}
};
int main(int argc,char** argv) {
vector<int> nums = {3,1,1,1,0,0,0,4};
Solution test;
cout << test.jumpgame(nums) << endl;
system("pause");
return 0;
}
结果如下:
当输入的nums为{3,1,1,1,0,0,0,4}时返回false;
当输入的nums为{2,1,1,3,4,0,1,3}时返回的是true;