Problem
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
.
Solution
题意
给定一个非负数组,你的当前位置是在第一个元素处,每一个元素的数字代表从当前位置出发能够达到的最远距离(笔者一开始就忽略了这个“最远”,以为是代表了当前位置唯一能够到达的距离)。
判断是否能够到达数组的最后一个元素。
分析
这又是一道动态规划题,有点像昨天晚上做过的那道最大子串问题,解决思路是一样的,维持一个reach变量:
reach = max(reach, i + A[i])
Note:为什么是i + A[i]?
结合之后的代码可以看到,首先循环能否继续进行的判断条件是i < size && i < reach
,也就是说,要对第i个数进行判断,需要满足的条件是能够到达第i个数。
所以,i + A[i]的意义是在到达当前位置的基础上,接下来的一步能够到达的最远总距离。
复杂度分析
- 时间复杂度:只需要将数组遍历一次,所以时间复杂度为O(n)
- 空间复杂度:维护一个reach变量,时间复杂度为O(1)
Code
class Solution {
public:
int myMax(const int &a, const int &b){
if (a >= b) return a;
return b;
}
bool canJump(vector<int>& nums) {
//动态规划的题,维护一个reach变量
//reach = max(reach, i + A[i])(通过i步到达当前位置,i+A[i]是当前能到达的最远距离
if (nums.empty()) return false;
int size = nums.size();
if (size == 1) return true;
int reach = 0;
for (int i = 0; i < size && i <= reach; i++){
reach = myMax(reach, i + nums[i]);
}
return (reach >= size - 1);
}
};