[leetcode] Jump Game II
程序员文章站
2024-03-01 09:09:52
...
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.
Solution
使用广搜。
class Solution {
public:
int jump(vector<int>& nums) {
// 数组为空,不需要移动。
if (!nums.size()) {
return 0;
}
queue<int> indexes;
int min_road_length = 0, temp, current_index = 0, length = nums.size() - 1, max = 0;
indexes.push(0);
indexes.push(-1);
// 广搜
while (current_index < length && indexes.size()) {
current_index = indexes.front();
indexes.pop();
if (current_index == -1) {
indexes.push(-1);
min_road_length = min_road_length + 1;
} else {
temp = nums[current_index];
if (current_index + temp >= length) {
min_road_length = min_road_length + 1;
break;
}
while (temp && current_index + temp > max) {
indexes.push(current_index + temp);
temp = temp - 1;
}
max = max < current_index + temp ? current_index + temp : max;
}
}
return min_road_length;
}
};
推荐阅读
-
[leetcode] Jump Game II
-
Leetcode Pascal's Triangle II
-
Pascal's Triangle II - LeetCode
-
DHU高级程序设计-leetcode刷题剑指 Offer 57 - II. 和为s的连续正数序列
-
LeetCode-63-Unique Paths II
-
Leetcode 454. 4Sum II
-
【LeetCode】 119. 杨辉三角 II 不正经的骚操作
-
LeetCode第219题--存在重复元素II
-
#leetcode刷题之路45-跳跃游戏 II
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST