贪心算法
在可到达范围内,选择跳跃距离到当前点最远的位置。
时间复杂度:O(N)
C++代码:
class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() == 1)
return 0;
if (nums[0] >= nums.size() - 1)
return 1;
int now = 0, jump = 0, next_pos = 0;
while (1)
{
for (int i = now; i <= now + nums[now]; i++)
{
if (nums[i] + i - now > nums[next_pos] + next_pos - now)
next_pos = i;
}
jump++;
now = next_pos;
if (now + nums[now] >= nums.size() - 1)
return jump + 1;
}
}
};