leetcode45 -- Jump Game2 (被面过)

# 小郑之家~

### 题目

Given an array of positive 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.



### 解法2


class Solution {
public:
int jump(vector<int>& nums) {
int res = 0, n = nums.size(), i = 0, cur = 0;
while (cur < n - 1) {
++res;
int pre = cur;
for (; i <= pre; ++i) {
cur = max(cur, i + nums[i]);
}

}
return res;
}
};



class Solution:
def jump(self, nums: List[int]) -> int:
res = 0
n = len(nums)

cur = 0

# cur 的意思是虽然当前在这个位置，但是其实说不定能够跳得更远一些
while cur<n-1:
res +=1
pre = cur

for i in range(pre+1):
cur = max(cur, i+nums[i])
return res