45. Jump Game II
https://leetcode.com/problems/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./*
* @lc app=leetcode id=45 lang=cpp
*
* [45] Jump Game II
*/
class Solution {
public:
int jump(vector<int>& nums) {
int res = 0, cur = 0, next = 0;
for (int i = 0; i < nums.size() - 1; ++i) {
next = max(next, i + nums[i]);
if (i == cur) {
cur = next;
++res;
}
}
return res;
}
};
Last updated