题目描述
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.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the >>last index.Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
题目大意
给出一个非负整数数组,数组元素表示能前进的步数;对于这样一个数组,判断是否能够到达最后一个元素。
思路分析
这是一道典型的贪心算法题,即选择当前最优的解;而这题中局部最优的解为当前所能到达的最远位置,即当前坐标(下标)与数组元素值的和。从0开始,更新可到达的最远距离,直到可到达最后一个元素(n-1)。
关键代码
bool canJump(vector<int>& nums) {
vector<int> maxReachable = nums;
int n = nums.size();
for (int i = 0; i < n; i++) {
maxReachable[i] += i;
}
int maxJump = maxReachable[0];
int index = 1;
for (; index <= maxJump; index++) {
if (maxJump < maxReachable[index]) {
maxJump = maxReachable[index];
if (maxJump >= n-1) {
return true;
}
}
}
return maxJump >= n-1;
}
总结
找出局部最优解的指标是解决贪心算法的关键。在这题中的maxReachable数组是有点冗余,若在数组开头就能找到解,则会有许多的冗余操作;并且它还提高了空间复杂度。