LeetCode hot 100—跳跃游戏 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

分析

贪心法

思路

初始化

  • 首先获取数组的长度 n。若 n 为 1,直接返回 0,因为已经在末尾。
  • 初始化 jumps 为 0,currentEnd 为 0,farthest 为 0。

遍历数组

  • 在遍历过程中,对于每个位置 i,计算 i + nums[i],它代表从当前位置 i 能跳到的最远索引。然后使用 std::max 函数更新 farthest,确保 farthest 始终是当前位置及其之前位置能跳到的最远位置。
  • 当 i 等于 currentEnd 时,意味着已经到达了当前这一跳的边界,此时需要进行一次新的跳跃,所以 jumps 加 1,并且将 currentEnd 更新为 farthest,也就是下一次跳跃的边界。

返回结果

  • 遍历结束后,jumps 就是到达数组末尾所需的最少跳跃次数,将其返回。

时间复杂度:O(n), n 是数组的长度

空间复杂度:O(1)

class Solution {
public:
    int jump(std::vector<int>& nums) {
        int n = nums.size();
        if (n == 1) {
            return 0;
        }
        int jumps = 0;
        int currentEnd = 0;
        int farthest = 0;
        for (int i = 0; i < n - 1; ++i) {
            // 更新从当前位置能跳到的最远位置
            farthest = std::max(farthest, i + nums[i]);
            // 当到达当前跳跃的边界时
            if (i == currentEnd) {
                // 进行一次跳跃
                jumps++;
                // 更新下一次跳跃的边界
                currentEnd = farthest;
            }
        }
        return jumps;
    }
};    
### 关于 LeetCode Hot100 的题目解析与代码实现 以下是针对部分经典 LeetCode Hot100 题目的详细解析和代码实现: --- #### **可被三整除的最大和** 此题的核心在于动态规划的应用。通过构建状态转移方程来解决子序列求和问题。 ```python from functools import lru_cache def maxSumDivThree(nums): @lru_cache(None) def dp(index, remainder): if index == len(nums): return 0 if remainder == 0 else float('-inf') take = nums[index] + dp(index + 1, (remainder + nums[index]) % 3) not_take = dp(index + 1, remainder) return max(take, not_take) return dp(0, 0) ``` 上述方法利用记忆化递归来优化时间复杂度,确保每种可能的状态仅计算一次[^1]。 --- #### **玩筹码** 该问题可以通过贪心算法高效解决。核心思路是统计奇偶位置上的筹码数量并选择代价较小的操作方式。 ```python def minCostToMoveChips(position): even_count = sum(p % 2 == 0 for p in position) odd_count = len(position) - even_count return min(even_count, odd_count) ``` 这里的时间复杂度为 O(n),其中 n 是 `position` 数组的长度。 --- #### **买卖股票的最佳时机** 这是一道经典的单次交易最大利润问题,可以采用线性扫描的方式完成。 ```python def maxProfit(prices): min_price = float('inf') max_profit = 0 for price in prices: if price < min_price: min_price = price elif price - min_price > max_profit: max_profit = price - min_price return max_profit ``` 这段代码的关键在于维护当前最低价格以及潜在的最大收益。 --- #### **跳跃游戏 I 和 II** 这两道题分别涉及布尔判断和最小步数计算。前者可通过记录可达范围快速判定,后者则需借助动态规划思想逐步推进最优路径。 ##### 跳跃游戏 I ```python def canJump(nums): farthest = 0 for i, jump in enumerate(nums): if i > farthest: return False farthest = max(farthest, i + jump) return True ``` ##### 跳跃游戏 II ```python def jump(nums): jumps = current_end = farthest = 0 for i in range(len(nums) - 1): farthest = max(farthest, i + nums[i]) if i == current_end and i != len(nums) - 1: jumps += 1 current_end = farthest return jumps ``` 两者的共同特点是基于局部最优解推导全局最佳策略。 --- #### **划分字母区间** 本题要求找到字符串中的不重叠分区数目,适合用双指针配合哈希表处理。 ```python def partitionLabels(s): last_occurrence = {c: i for i, c in enumerate(s)} partitions = [] start = end = 0 for i, char in enumerate(s): end = max(end, last_occurrence[char]) if i == end: partitions.append(end - start + 1) start = i + 1 return partitions ``` 这种方法能够在线性时间内解决问题,并且保持空间开销较低。 --- #### **移动零** 对于数组操作类问题,“头部”扩展技巧非常实用。具体做法如下所示: ```python def moveZeroes(nums): head = 0 for i in range(len(nums)): if nums[i] != 0: nums[head], nums[i] = nums[i], nums[head] head += 1 ``` 此处逻辑清晰明了,只需两次遍历即可达成目标[^2]。 --- ### 总结 以上展示了若干热门 LeetCode 题目及其解决方案。这些例子涵盖了多种常见算法模式,包括但不限于动态规划、贪心算法、滑动窗口等技术手段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rigidwill666

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值