> 文章列表 > 算法leetcode|45. 跳跃游戏 II(rust重拳出击)

算法leetcode|45. 跳跃游戏 II(rust重拳出击)

算法leetcode|45. 跳跃游戏 II(rust重拳出击)


文章目录

  • 45. 跳跃游戏 II:
    • 样例 1:
    • 样例 2:
    • 提示:
  • 分析:
  • 题解:
    • rust
    • go
    • c++
    • c
    • python
    • java

45. 跳跃游戏 II:

给定一个长度n0 索引整数数组 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 <= 104
  • 0 <= nums[i] <= 1000
  • 题目保证可以到达 nums[n-1]

分析:

  • 面对这道算法题目,二当家的陷入了沉思。
  • 看到提示说保证有解,就想到逆向,由终点回起点,慢。
  • 看是找最优解,又想到用动态规划。
  • 但是题目说每个数字表示的是跳转的最大长度,而不是固定长度,这时候就想到了使用贪心,先选能跳到最远的,但下一步我不一定非得跳固定长度,完全可以跳的近,它包含了跳的近的位置,走一步说一步,局部最优,太贪心了。

题解:

rust

impl Solution {pub fn jump(nums: Vec<i32>) -> i32 {let (mut maxPos, mut end, mut steps) = (0, 0, 0);(0..nums.len() - 1).for_each(|i| {maxPos = maxPos.max(i + nums[i] as usize);if i == end {end = maxPos;steps += 1;}});return steps;}
}

go

func jump(nums []int) int {l := len(nums)maxPos, end, steps := 0, 0, 0for i := 0; i < l-1; i++ {if maxPos < i+nums[i] {maxPos = i + nums[i]}if i == end {end = maxPossteps++}}return steps
}

c++

class Solution {
public:int jump(vector<int>& nums) {int n = nums.size(), maxPos = 0, end = 0, step = 0;for (int i = 0; i < n - 1; ++i) {maxPos = max(maxPos, i + nums[i]);if (i == end) {end = maxPos;++step;}}return step;}
};

c

int jump(int* nums, int numsSize){int maxPos = 0, end = 0, step = 0;for (int i = 0; i < numsSize - 1; ++i) {maxPos = fmax(maxPos, i + nums[i]);if (i == end) {end = maxPos;++step;}}return step;
}

python

class Solution:def jump(self, nums: List[int]) -> int:n = len(nums)max_pos, end, step = 0, 0, 0for i in range(n - 1):max_pos = max(max_pos, i + nums[i])if i == end:end = max_posstep += 1return step

java

class Solution {public int jump(int[] nums) {int maxPos = 0, end = 0, steps = 0;for (int i = 0; i < nums.length - 1; ++i) {maxPos = Math.max(maxPos, i + nums[i]);if (i == end) {end = maxPos;++steps;}}return steps;}
}

非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


浏阳门户网