给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
————————————
解题思路:
(1)使用贪心算法;
(2)使用max_pos保存当前步所能到达的最远距离,比如例子中的nums[0]表示从index=0的位置所能到达的最远距离为index=2,这时候走了一步,使用step记录走的步数,step=1;
(3)在nums[1-2]的距离内,记录在num[1-2]所能到达的最远距离,由例子可以知道,nums[1-2]能到达的最远距离为index=4,也就是到达index=4的位置所需要的最少步数为step=2;因为index=4为数组的最后一位,因此可以返回2作为结果;
其Python3代码如下:
# Python3
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
# maxPos用于保存当前nums[,end]所能到达的最远距离;
# step用于记录最大步数
maxPos, end, step = 0, 0, 0
for i in range(n - 1):
# end是当前step的最远距离
if i <= end:
# 更新当前nums[:end]可以到达的最远距离maxPos
maxPos = max(maxPos, i + nums[i])
# 当到达边界,则更新下一步的边界,并更新步数
if i == end:
end = maxPos
step += 1
return step
其C++代码如下:
class Solution {
public:
int jump(vector<int>& nums)
{
int length = nums.size();
int max_pos = 0;
int end = 0;
int time = 0;
for(int i=0;i<length-1;++i)
{
if(i<=end)
{
max_pos = max(max_pos,nums[i]+i);
if(i==end)
{
end = max_pos;
time++;
}
}
}
return time;
}
};
代码时间复杂度为O(n),n为数组长度;空间复杂度为O(1);