代码随想录算法训练营|day34

860.柠檬水找零

定义five,ten为顾客付5元和10元的张数,找零时首先找较大面额,分情况讨论:
如果顾客付5元,直接five++
如果顾客付10元,自己至少有一张5元,five–,ten++;否则返回false
如果顾客付20元,自己至少有一张5元和一张10元,five–,ten–;或者自己至少有3张5元,five-=3;否则返回false

func lemonadeChange(bills []int) bool {
	five, ten := 0, 0
	for i := 0; i < len(bills); i++ {
		if bills[i] == 5 {
			five++
		} else if bills[i] == 10 {
			if five > 0 {
				ten++
				five--
			} else {
				return false
			}
		} else {
			if ten > 0 && five > 0 {
				ten--
				five--
			} else if five > 2 {
				five -= 3
			} else {
				return false
			}
		}
	}
	return true
}

406.根据身高重建队列

先对数组中数对的第一个元素降序排序,然后对数对的第二个元素插入升序排序

func reconstructQueue(people [][]int) [][]int {
	// 1.高个子对矮个子没影响,先降序排序
	sort.Slice(people, func(i, j int) bool {
		// 身高相同时,序号小在前
		if people[i][0] == people[j][0] {
			return people[i][1] < people[j][1]
		}
		return people[i][0] > people[j][0]
	})
	// 2.然后把矮个子插入对应位置person[i][1]即可
	res := make([][]int, len(people))
	for i := 0; i < len(people); i++ {
		if len(res) <= people[i][1] {
			res = append(res, people[i])
		} else {
			// 在指定位置插入元素
			index := people[i][1]
			copy(res[index+1:], res[index:])
			res[index] = people[i]
		}
	}
	return res
}

原地排序

for index, person := range people {
		copy(people[person[1]+1:index+1], people[person[1]:index+1])
		people[person[1]] = person
}

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

贪心:对气球右边界排序,初始时最大右边界为points[0][1],后续遍历的气球右边界都比初始值大,只要保证气球左边界小于maxRight就能被箭射穿,否则更新最大右边界,箭个数++

func findMinArrowShots(points [][]int) int {
	sort.Slice(points, func(i, j int) bool {
		return points[i][1] < points[j][1]
	})
	res := 1
	maxRight := points[0][1]
	for i := 1; i < len(points); i++ {
		if points[i][0] <= maxRight {
			continue
		}
		maxRight = points[i][1]
		res++
	}
	return res
}

代码随想录文章详解

860.柠檬水找零
406.根据身高重建队列
452.用最少数量的箭引爆气球

  • 37
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值