子商务网站建设实践,全球军情动态,如何做自己公司的网站,网站开发下载leetcode原题链接#xff1a;跳跃游戏 II
题目描述 给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。 每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说#xff0c;如果你在 nums[i] 处#xff0c;你可以跳转到任意 nums[i j] 处:
0 j 跳跃游戏 II
题目描述 给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。 每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说如果你在 nums[i] 处你可以跳转到任意 nums[i j] 处:
0 j nums[i] i j n 返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]。
示例 1:
输入: nums [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是2。 从下标为 0 跳到下标为 1 的位置跳1步然后跳3步到达数组的最后一个位置。
示例 2:
输入: nums [2,3,0,1,4]
输出: 2提示:
1 nums.length 1040 nums[i] 1000题目保证可以到达 nums[n-1]
解题方法贪心法。遍历数组中的每一个数一边遍历一边更新当前可跳转的最大距离记为max_pos然后把每一个max_pos比做一面墙每跨过一面墙则需要跳一步。跨过这面墙后需要寻找新的墙即寻找新的max_pos)再寻找墙的过程中如果超越了终点位置则结束寻找。 C代码
#include iostream
#include vector
class Solution {
public:int jump(std::vectorint nums) {int n nums.size();int max_pos 0; //下次能到达的最大下标的位置int step 0;//跳的步数int last_max_pos 0;//保存跳转前上次计算的最大跳转位置for (int i 0; i n - 1; i) {max_pos std::max(max_pos, nums[i] i);if (i last_max_pos) { //把last_max_pos当作一面墙每次经过这面墙就跳过去last_max_pos max_pos;step;}}return step;}
};