原题:
Problem Description
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.
Sample Input
[2,3,1,1,4]
[3,2,1,0,4]- Sample Output
true
false 解题思路:
贪心:
在当前位置,判断可跳至的最远位置之前的位置中,哪些位置是可以跳到更远;
然后选取可以跳至最远的位置,更新为当前位置;
然后重复此过程,直至能够跳至结尾。代码思路:
1、遍历数组,每次寻找可以到达的更远位置,然后更新数据。
2、循环终止条件:遍历到数组结尾 + 无法跳至比更远位置再远的位置。代码:
#include <vector> using namespace std; class Solution { public: bool canJump(vector<int>& nums) { vector<int> index;//最远可跳至的位置【动态数组】 for (int i = 0; i < nums.size(); i++) index.push_back(i + nums[i]); int jump = 0;//当前位置 int max_index = index[0];//当前可到达的最远的位置 while (jump <= nums.size() - 1 && jump <= max_index) {//如果当前位置<=数组最后一个位置&&当前位置<=当前可到达的最远的位置 if (max_index < index[jump]) max_index = index[jump];//逐个位置扫描,对可跳的最远位置进行更新 jump++; } if (jump == nums.size())//若当前位置达到数组最后一个位置 return true; return false; } };