# 45. Jump Game II 跳跃游戏 II

@TOC

## # 题目描述

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.

## # 解题方法

### # 贪心

``````class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
reach = 0
cur = 0
N = len(nums)
count = 0
pos = 0
while cur < N - 1:
count += 1
pre = cur
while pos <= pre:
cur = max(cur, pos + nums[pos])
pos += 1
return count
``````

C++版本的代码如下：

``````
class Solution {
public:
int jump(vector<int>& nums) {
int N = nums.size();
int pos = 0;
int count = 0;
int pre = 0, cur = 0;
while (cur < N - 1) {
count ++;
pre = cur;
while (pos <= pre) {
cur = max(cur, pos + nums[pos]);
pos ++;
}
}
return count;
}
};
``````

## # 日期

2018 年 11 月 28 日 —— 听说楼下有传染病。。