题目描述:
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
.
解题思路:
贪心思路,当当前maxStep == 0时, 返回false,如果当前位置加上maxStep>数组长度,返回false
1 class Solution { 2 public: 3 bool canJump(vector<int>& nums) { 4 if (nums.size() == 0 || nums.size() == 1) { 5 return true; 6 } 7 8 int maxStep = nums[0]; 9 10 for (int i = 1; i < nums.size(); ++i) { 11 if (maxStep == 0) { 12 return false; 13 } 14 15 maxStep -= 1; 16 if (maxStep < nums[i]) { 17 maxStep = nums[i]; 18 } 19 20 if (i + maxStep >= nums.size() - 1) { 21 return true; 22 } 23 } 24 25 return true; 26 } 27 };