算法训练营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

}

相关推荐
进击的荆棘36 分钟前
递归、搜索与回溯——递归
算法·leetcode·递归
2301_822703202 小时前
鸿蒙Flutter第三方库FlutterUnit组件百科适配——具体示例还原演示1
算法·flutter·华为·harmonyos·鸿蒙
2301_764441338 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI8 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly9 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives9 小时前
atcoder ABC 452 题解
数据结构·算法
feifeigo1239 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
fengfuyao98510 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
无敌昊哥战神11 小时前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜11 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展