【LeetCode】45. Jump Game II(C++)
阿新 • • 發佈:2019-01-01
地址:https://leetcode.com/problems/jump-game-ii/
題目:
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的思想,從當前位置可以跳到下一步的範圍可以確定,從下一步的範圍內的位置可以跳到下下一步的範圍也可以確定,因此可以每次根據當前的範圍判斷下一步的範圍。
雖然題裡給出的是總是可達的,這裡還是給出一種通用的方法吧,並不假設總是可達的。
class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() == 1) return 0;
int step = 0;
int left = 0, right = 0;
int maxEnd = 0;
while (right<nums.size() - 1) {
++step;
for (int i = left; i <= right; ++i) {
if (i + nums[i] >= nums.size() - 1) return step;
maxEnd = max(maxEnd, nums[i] + i);
}
if (maxEnd == right)
break;
left = right + 1;
right = maxEnd;
}
return -1;
}
};