算法训练营day30,贪心算法4

import "sort"

// 860. 柠檬水找零

func lemonadeChange(bills []int) bool {

//如果最开始就大于5元,肯定无法找零直接返回false

if len(bills) > 0 && bills[0] > 5 {

return false

}

five := 0

ten := 0

twenty := 0

for i := 0; i < len(bills); i++ {

//等于5元直接收下不用找零,five++

if bills[i] == 5 {

five++

//如果是10元,且有5元可以找零

} else if bills[i] == 10 && five > 0 {

ten++

five--

} else if bills[i] == 20 && five > 0 {

//如果是20元,可以找10元+5元或者3个五元,优先采用10+5方式

if ten > 0 {

twenty++

ten--

five--

} else {

if five < 3 {

return false

}

five -= 3

}

//如果没有五元找零,直接返回false

} else if five == 0 && (bills[i] == 10 || bills[i] == 20) {

return false

}

}

return true

}

//406. 根据身高重建队列

func reconstructQueue(people [][]int) [][]int {

sort.Slice(people, func(i, j int) bool {

if people[i][0] == people[j][0] { //如果身高相等则按照k从小到大排序

return people[i][1] < people[j][1]

}

return people[i][0] > people[j][0] //身高由大到小排序

})

// 再按照K进行插入排序,优先插入K小的

for i := 0; i < len(people); i++ {

p := people[i]

copy(people[p[1]+1:i+1], people[p[1]:i+1])

people[p[1]] = p

}

return people

}

//452. 用最少数量的箭引爆气球

func findMinArrowShots(points [][]int) int {

if len(points) == 0 {

return 0

}

arrow := 1 //弓箭数量

//按第一位从小到大排序

sort.Slice(points, func(i, j int) bool {

return points[i][0] < points[j][0]

})

for i := 1; i < len(points); i++ {

//如果前一个右边界比当前左边界小说明无法一起射破,需要增加一支箭

if points[i-1][1] < points[i][0] {

arrow++

} else {

// 如果当前边界比之前边界大,则沿用之前边界

if points[i][1] > points[i-1][1] {

points[i][1] = points[i-1][1]

}

}

}

return arrow

}

相关推荐
学不动CV了6 分钟前
数据结构---链表结构体、指针深入理解(三)
c语言·arm开发·数据结构·stm32·单片机·链表
weixin_4461224636 分钟前
LinkedList剖析
算法
百年孤独_2 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
风飘百里2 小时前
分组加密核心原理与实践解析(AES/SM4)
go
我爱C编程2 小时前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测
算法_小学生2 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
算法_小学生2 小时前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode
岁忧2 小时前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
alphaTao2 小时前
LeetCode 每日一题 2025/6/30-2025/7/6
算法·leetcode·职场和发展