题意
有n个点,每个点有从这个点最多能前进的距离,求从第一个点到最后一个点的最少步数
思路
首先应该想到搜索,但是
- maxLoc:当前选择的落脚点能到达的最远处
- maxPos:当前遍历点能到达的最远处
- ans:记录当前已走的步数
在遍历过程中更新maxPos,当遍历点到达maxLoc的时候,更新步数和maxLoc,同时初始化maxPos,以便后面的更新.
代码
class Solution {
public:
int jump(vector<int>& nums) {
size_t len = nums.size();
int maxLoc = 0, maxPos = 0, ans = 0;
for(int i = 0; i < len; i++){
if(maxLoc >= len - 1) break;
maxPos = max(maxPos, i + nums[i]);
if(i == maxLoc){
ans++;
maxLoc = maxPos;
maxPos = -1;
}
}
return ans;
}
};