45. Jump Game II
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.
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.
思路:
采用BFS算法。每次计算出能到达的最远距离reach,则下一次的end为reach,start为上一次的end+1,保存能够到达的区域[start, end],然后判断是否能到达终点。
Solution (C++):
int jump(vector<int>& nums) {
if (nums.empty()) return 0;
int n = nums.size(), step = 0, start = 0, end = 0, reach;
while (end < n-1) {
step++;
reach = end + 1;
for (int i = start; i <= end; ++i) {
if (i + nums[i] >= n-1) return step;
reach = max(reach, i + nums[i]);
}
start = end + 1;
end = reach;
}
return step;
}
性能:
Runtime: 12 ms Memory Usage: 10.2 MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
![](https://www.cnblogs.com/images/cnblogs_com/dysjtu1995/1468066/t_qrcode_for_gh_547d3edeac81_258.jpg)
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。