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.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Note:
You can assume that you can always reach the last index.
题目链接:https://leetcode-cn.com/problems/jump-game-ii/
思路
原本思路是BFS,把每个位置能到达的新位置方案加入队列中,同时每个新位置只考虑一次,复杂度O(n)。
但这个方法在大数据下超时了。
class Solution {
public:
int jump(vector<int>& nums) {
int len = nums.size();
if(len<=1) return 0;
vector<bool> rec(len, false);
int res = 0, cur = 0;
rec[0] = true;
queue<int> q;
q.push(cur);
while(!q.empty()){
++res;
int n = q.size();
for(int k=0; k<n; ++k){
cur = q.front();
q.pop();
int tmp = nums[cur];
for(int i=1; i<=tmp; ++i){
if(cur+i == len-1){
return res;
}else if(cur+i<len-1 && !rec[cur+i]){
q.push(cur+i);
rec[cur+1] = true;
}
}
}
}
return res;
}
};
后来看了解析,使用了贪心的思想,复杂度也同样是O(n),但是判断和状态存储少。
核心思路是每一步计算其能到达的最远地方,在计算最远的时候也是将每个可能位置逐个判断,也可以说是一种BFS的思维,但实现上比我的方法精简得不少。
maxPos用于记录当前能去到的最远位置,end用于记录所走步数增加的分界位置。
class Solution {
public:
int jump(vector<int>& nums) {
int maxPos = 0, n = nums.size(), end = 0, step = 0;
for (int i = 0; i < n - 1; ++i) {
if (maxPos >= i) {
maxPos = max(maxPos, i + nums[i]);
if (i == end) {
end = maxPos;
++step;
}
}
}
return step;
}
};