贪心
1、860. 柠檬水找零
题目:
输入:bills = [5,5,5,10,20]
输出:true
思路:
- 模拟大法
func lemonadeChange(bills []int) bool {
//贪心,代码一刷, 感觉要用到hashmap,也不用
five, ten := 0,0
for i:=0; i<len(bills); i++ {
if bills[i] == 5 {
five++
} else if bills[i] == 10 {
if five >= 1 {
five--
ten++
} else {
return false
}
} else if bills[i] == 20 {
if five > 0 && ten > 0 {
five--
ten--
} else if five >= 3 {
five -= 3
} else {
return false
}
}
}
return true
}
2、406. 根据身高重建队列
题目:
题目读了5遍,giao,才读懂
思路:
- 贪心,先按照h,k排序,再按照k排序
func reconstructQueue(people [][]int) [][]int {
// 代码一刷
sort.Slice(people, func(a,b int) bool {
if people[a][0] == people[b][0] {
return people[a][1] < people[b][1]
}
return people[a][0] > people[b][0]
})
for i, p := range people {
copy(people[p[1]+1 : i+1], people[p[1] : i+1])
people[p[1]] = p
}
return people
}
3、452. 用最少数量的箭引爆气球
题目:
用最少数量的箭引爆气球
输入:points = [[10,16],[2,8],[1,6],[7,12]]
输出:2
思路:
- 画图+模拟,sort.Slice用的6了
func findMinArrowShots(points [][]int) int {
res := 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][0] > points[i-1][1] {
res++
} else{
points[i][1] = min(points[i][1], points[i-1][1]);
}
}
return res
}
func min(a,b int) int {if a>b {return b}; return a}