力扣爆刷第147天之贪心算法五连刷(跳跃、发糖果、加油站)

力扣爆刷第147天之贪心算法五连刷(跳跃、发糖果、加油站)

一、45. 跳跃游戏 II

题目链接:https://leetcode.cn/problems/jump-game-ii/description/
思路:本题求的是跳跃的最少次数,要想求最少次数当然是在每一个跳跃区间内寻找最远的下一跳,这样每次走完当前区间,要进行下一跳时,选择距离最远的选择进行跳跃,并且记录下跳跃次数,本质上是不断更新最远区间的过程,只不过更新时选择最远的进行更新。

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

二、1005. K 次取反后最大化的数组和

题目链接:https://leetcode.cn/problems/maximize-sum-of-array-after-k-negations/description/
思路:本题本质上是让把负数的部分先翻转,来消耗K,如果k没有被消耗完,就会出现两种情况,要么全为负数,要么负数消耗完了,如果全为负数,则只需要把剩余的k用在最后一个元素上,如果是负数消耗完了,则需要以0为界限,相邻的两个数的绝对值的最小值,来作为消耗值。由此即可解题。

class Solution {
    public int largestSumAfterKNegations(int[] nums, int k) {
        Arrays.sort(nums);
        int i = 0, len = nums.length;
        for(; i < len; i++) {
            if(k == 0 || nums[i] >= 0) break;
            nums[i] = -nums[i];
            k--;
        }
        if(k > 0) {
            if(i < len) {
                if(i - 1 > 0 && nums[i-1] < nums[i]) i = i-1;
                nums[i] = k % 2 == 0 ? nums[i] : -nums[i];
            }else{
                nums[len-1] = k % 2 == 0 ? nums[len-1] : -nums[len-1];
            }
        }
        int sum = 0;
        for(int t : nums) {
            sum += t;
        }
        return sum;
    }
}

三、134. 加油站

题目链接:https://leetcode.cn/problems/gas-station/description/
思路:加油站问题其实就是油和消耗的问题,只需要认识到,如果油的总和大于等于消耗总和,是一定可以走完全场的,如果油的总和小于消耗的总和,是一定走不完全场的。
那么要寻找起点,只需要从第一个油量大于消耗量的点开始,向后累加差值,只需要差值小于0,就从下一个位置开始,这样只要遍历结束,油的总量还大于消耗,就一定记录了开始位置。

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int cur = 0, total = 0, start = 0;
        for(int i = 0; i < gas.length; i++) {
            cur += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if(cur < 0) {
                start = i+1;
                cur = 0;
            }
        }
        if(total < 0) return -1;
        return start;
    }
}

四、135. 分发糖果

题目链接:https://leetcode.cn/problems/candy/
思路:分发糖果,要求如果一个数比左右的数都要大,那么他获得的糖果数量应该是大于左右的,对于这种双边问题,我们可以一条边一条边的处理,先从左往右寻找右值大于左值的,再从右往左,寻找左值大于右值的,第一次但凡出现符合条件的糖果数量+1,第二次,不仅要出现还得是糖果数不符合条件时才加,为了避免多用糖果。

class Solution {
    public int candy(int[] ratings) {
        int len = ratings.length;
        if(len == 1) return 1;
        int[] nums = new int[len];
        for(int i = 1; i < len; i++) {
            if(ratings[i] > ratings[i-1]) nums[i] = nums[i-1]+1;
        }
        for(int i = len-2; i >= 0; i--) {
            if(ratings[i] > ratings[i+1] && nums[i] <= nums[i+1]) nums[i] = nums[i+1]+1; 
        }
        int sum = len;
        for(int t : nums) sum += t;
        return sum;
    }
}

五、860. 柠檬水找零

题目链接:https://leetcode.cn/problems/lemonade-change/description/
思路:遍历应对,枚举所有的实例,分条判断即可。

class Solution {
    public boolean lemonadeChange(int[] bills) {
        int a = 0, b = 0, c = 0;
        for(int i : bills) {
            if (i == 5) {
                a++;
            } else if(i == 10) {
                a--;
                b++;
            } else {
                c++;
                if(b > 0) {
                    b--;
                    a -= 1;
                }else{
                    a -= 3;
                }
            }
            if(a < 0) return false;
        }
        return true;
    }
}
### 关于贪心算法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
发出的红包

打赏作者

当年拼却醉颜红

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

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

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

打赏作者

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

抵扣说明:

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

余额充值