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

import "sort"

// 860. 柠檬水找零

func lemonadeChange(bills \[\]int) bool {

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

if len(bills) > 0 && bills0 > 5 {

return false

}

five := 0

ten := 0

twenty := 0

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

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

if billsi == 5 {

five++

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

} else if billsi == 10 && five > 0 {

ten++

five--

} else if billsi == 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 && (billsi == 10 || billsi == 20) {

return false

}

}

return true

}

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

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

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

if peoplei0 == peoplej0 { //如果身高相等则按照k从小到大排序

return peoplei1 < peoplej1

}

return peoplei0 > peoplej0 //身高由大到小排序

})

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

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

p := peoplei

copy(peoplep\[1+1:i+1], peoplep\[1:i+1])

peoplep\[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 pointsi0 < pointsj0

})

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

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

if pointsi-11 < pointsi0 {

arrow++

} else {

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

if pointsi1 > pointsi-11 {

pointsi1 = pointsi-11

}

}

}

return arrow

}

相关推荐
qeen872 小时前
【数据结构】自平衡二叉搜索树各种旋转算法原理解析及AVL树的C++实现
数据结构·c++·算法
lucas_AI3 小时前
1.2B 小模型赢过 235B 大模型:NaviDC-OCR 把文档解析卷明白了
人工智能·深度学习·算法
冻柠檬飞冰走茶3 小时前
PTA基础编程题目集 7-35有理数均值(C++语言实现)
开发语言·数据结构·c++·算法·均值算法
民乐团扒谱机4 小时前
【微实验】倒谱算法(Cepstrum)深度解析:原理、数学推导与代码实现
人工智能·算法·语音识别
worxfr4 小时前
Go 底层心智模型:并发、内存与闭包
go
Nil2084 小时前
leetcode 189轮转数组
数据结构·算法·leetcode
-dzk-5 小时前
【动态规划】LC 118.杨辉三角
算法·动态规划
恣逍信点5 小时前
《凌微经》静态自悖——变化之自因
人工智能·科技·算法·机器学习·业界资讯·拓扑学·哲学
吃着火锅x唱着歌5 小时前
LeetCode 3885.设计事件管理器
算法·leetcode·职场和发展
土司大王5 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode