45. Jump Game II
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.// Greedy Method
int jump(vector<int>& nums) { // time: O(n); space: O(1)
int res = 0, n = nums.size(), last = 0, curReach = 0;
for (int i = 0; i < n - 1; ++i) {
curReach = max(curReach, i + nums[i]);
if (i == last) {
last = curReach;
++res;
if (curReach >= n - 1) break;
}
}
return res;
}Last updated