题意:
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.
For example:
Given array A = [2,3,1,1,4]
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.)
解法:
使用类似于BFS的形式。
维护beg,end两个位置,其表示我们在step步能到达的范围,
然后我们再多走一步,step = step + 1,那么更新beg和end,beg = old_end + 1, end为之前范围再多走一步到达的最远位置。
时间复杂度:O(n)
int jump(vector<int>& nums) {
int step = 0, beg = 0, end = 0, newend = 0;
while(end < nums.size() - 1){
step++;
newend++;
for(int i = beg; i <= end; ++i){
if(i + nums[i] >= nums.size() - 1) return step;
newend = max(newend, i + nums[i]);
}
beg = end + 1;
end = newend;
}
return step;
}