java相关-贪心算法-跳跃游戏II-力扣45

package com.company;


import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class Main {

    public static void main(String[] args) {

        int[] nums = {7, 0, 9, 6, 9, 6, 1, 7, 9, 0, 1, 2, 9, 0, 3};
        int result = jump(nums);
        System.out.println(result);

    }

    public static int jump(int[] nums) {
        if (nums == null || nums.length == 0 || nums.length == 1) {
            return 0;
        }
        //跳跃次数
        int count = 0;
        //当前覆盖的最大区域
        int curDistance = 0;
        //最大覆盖区域
        int maxDistance = 0;
        for (int i = 0; i < nums.length; i++) {
            //在可覆盖区域内更新最大的覆盖区域
            maxDistance = Math.max(i + nums[i], maxDistance);
            //说明当前一步,再跳一步就到达了末尾
            if (maxDistance >= nums.length - 1) {
                count++;
                break;

            }
            //走到当前覆盖的最大区域时,更新下一步可达的最大区域
            if (i == curDistance) {
                curDistance = maxDistance;
                count++;
            }
        }

        return count;
    }

}



### 关于贪心算法在 LeetCode 平台上的题目解析 #### 1. **最长回文串** 此题的目标是从给定字符串中找到可以构成的最大长度的回文子序列。通过贪心策略,我们可以尝试尽可能多地匹配字符来构建回文结构。 实现方式如下: - 使用 `Counter` 来统计每个字符出现的次数。 - 对于偶数次出现的字符可以直接计入回文中;对于奇数次出现的字符,最多只能取其最大偶数值加入到回文中[^1]。 ```python from collections import Counter def longestPalindrome(s: str) -> int: counts = Counter(s) length = 0 odd_found = False for count in counts.values(): if count % 2 == 0: length += count else: length += count - 1 odd_found = True if odd_found: length += 1 return length ``` --- #### 2. **柠檬水找零** 该问题描述了一个场景:顾客购买价值 $5 的商品并支付不同面额的钱币 ($5, $10, 和 $20),我们需要判断能否成功完成所有交易而不缺少找零。 解决方法基于贪心原则——优先处理大金额钱币以便保留更多小额硬币用于后续操作[^3]: ```java class Solution { public boolean lemonadeChange(int[] bills) { int five = 0; int ten = 0; for (int bill : bills) { if (bill == 5) { five++; } else if (bill == 10) { if (five == 0) return false; five--; ten++; } else { // bill == 20 if (ten > 0 && five > 0) { ten--; five--; } else if (five >= 3) { five -= 3; } else { return false; } } } return true; } } ``` --- #### 3. **分发饼干** 目标是将若干大小不同的饼干分配给孩子,使得尽可能多的孩子感到满意(即孩子的胃口需求小于等于饼干尺寸)。采用排序加双指针的方法能够高效解决问题[^4]。 代码示例如下: ```python from typing import List class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() child, cookie = 0, 0 while child < len(g) and cookie < len(s): if g[child] <= s[cookie]: child += 1 cookie += 1 return child ``` --- #### 4. **根据身高重建队列** 这道题要求按照特定规则重新排列一组人员的位置。先按高度降序排列再插入对应索引位置即可达成目的。 以下是 Python 版本解决方案: ```python class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: people.sort(key=lambda x: (-x[0], x[1])) result = [] for p in people: result.insert(p[1], p) return result ``` --- #### 5. **摆动序列** 定义一个数组中的“峰值”和“谷值”,并通过遍历一次数组计算出可能存在的波峰数量作为最终答案的一部分[^5]。 具体做法如下所示: ```python class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: if not nums: return 0 up, down = 1, 1 for i in range(1, len(nums)): if nums[i] > nums[i - 1]: up = down + 1 elif nums[i] < nums[i - 1]: down = up + 1 return max(up, down) ``` --- ### 总结 上述各例展示了如何利用贪心算法有效求解实际编程竞赛中的经典难题。每种情况都遵循局部最优决策从而达到全局较佳效果的原则[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值