45. Jump Game II (Array; Two-Pointers,Greedy)
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.)
思路:此处不能用Greedy I的贪心算法,因为局部的最少跳数(到i位置的最少跳数),并不适用于全局(并不是从i往后跳也是最少跳数)。这里我们要检查所有上一个step能到的位置,即startPos与endPos之间的所有位置,而不是仅仅看最远的那个位置。在求endPos的时候,我们还是用了贪心法,即当前step能到达的最远位置。
class Solution { public: int jump(vector<int>& nums) { int size = nums.size(); int endPos = 0; int newEndPos = 0; int startPos = 0; int step = -1; while(startPos<size){ for(int i = startPos; i <= endPos && i<size-1; i++){ //如果已经到了size-1位置(终点位置),那么不需要再计算了 newEndPos = max(newEndPos, i+nums[i]); } startPos = endPos+1; endPos = newEndPos; newEndPos = 0; step++; } return step; } };