586 字
3 分钟
代码随想录算法训练营第二十五天 | 贪心算法 Part03

134. 加油站#

LeetCode 134. Gas Station

  • 计算总油量与总消耗,如果油量不足,直接返回 -1;
  • 遍历每一站,记录当前的剩余油量;
  • 一旦当前剩余油量为负,说明不能从该段开始,重设起点。
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
total, min_sum, start = 0, 0, 0
for i in range(n):
total += gas[i] - cost[i]
if total < min_sum:
# 当前总油量比历史最小值还小,更新起点为下一站
min_sum = total
start = i + 1
if total < 0:
return -1
return 0 if start == n else start

135. 分发糖果#

LeetCode 135. Candy

  • 从左到右:如果右边评分更高,糖果数加 1;
  • 从右到左:如果左边评分更高,则更新为右侧糖果 + 1;
  • 最终两次遍历取最大值。
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
if n == 0:
return 0
candies = [1] * n # 每人至少一个
# 从左到右,确保右边高分的孩子糖果更多
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
candies[i] = candies[i - 1] + 1
# 从右到左,再次调整左边高分但糖果少的情况
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
candies[i] = max(candies[i], candies[i + 1] + 1)
return sum(candies)

860. 柠檬水找零#

LeetCode 860. Lemonade Change

  • 尽可能优先使用 10 元纸币进行找零;
  • 否则用 3 张 5 元;
  • 如果都无法找零,返回 False。
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
five, ten = 0, 0 # 初始化零钱数量
for bill in bills:
if bill == 5:
five += 1
elif bill == 10:
if five <= 0:
return False
five -= 1
ten += 1
else: # bill == 20
# 优先使用一个 10 和一个 5 找零
if ten > 0 and five > 0:
ten -= 1
five -= 1
elif five >= 3:
five -= 3
else:
return False
return True

406. 根据身高重建队列#

LeetCode 406. Queue Reconstruction by Height

  • 将数组按身高降序,k 升序排序;
  • 然后将每个人插入到结果列表的第 k 个位置。
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
# 按身高降序,k值升序排序
people.sort(key=lambda x: (-x[0], x[1]))
self.insertSort(people)
return people
def insertSort(self, people):
n = len(people)
sorted_index = 0
while sorted_index < n:
# 将当前元素插入到前面正确的位置,使得前面有 k 个高于等于它的人
for i in range(sorted_index, 0, -1):
k = people[i][1]
if k < i:
# 向前交换
people[i], people[i - 1] = people[i - 1], people[i]
else:
break
sorted_index += 1
代码随想录算法训练营第二十五天 | 贪心算法 Part03
https://fuwari.vercel.app/posts/code_musings_day_twenty-five/
作者
Jarrett
发布于
2025-07-09
许可协议
CC BY-NC-SA 4.0