# leetcode 随笔 Jump Game II

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.

runtime 13ms

class Solution {
public:
int jump(vector<int>& nums) {
if (nums.empty()||nums[0]==0||nums.size()==1) return 0;
int size = nums.size();
int count = 0;
int index = 0;
if (nums[0] >= size - 1)return 1;
while (index != size - 1)
{
count++;
if (nums[index] + index >= size - 1) return count;
int record = nums[index + 1] + index + 1, next_index = index + 1;
for (int i = 0; i < nums[index]-1; i++)
{
if (index + i + 2 + nums[index + i + 2] >= record)
{
record = index + i + 2 + nums[index + i + 2];
next_index = index + i + 2;
}
}
if (next_index == record) return 0;
index = next_index;
}
return count;
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120