860.柠檬水找零
需要找零的有10和20两种情况。20的有限把10元的找出去,因为10只能作为20的零钱。
func lemonadeChange(bills []int) bool {
hash := make(map[int]int, 0)
for i := 0; i < len(bills); i++{
hash[bills[i]]++
if bills[i] == 20{
if hash[10] >= 1 && hash[5] >= 1{
hash[10]--
hash[5] --
}else if hash[5] >= 3{
hash[5] -= 3
}else{
return false
}
}
if bills[i] == 10{
if hash[5] >= 1{
hash[5]--
}else{
return false
}
}
}
return true
}
406.根据身高重建队列
排序之后从小到大放置。
因为先将小的放进去后,大的放位置只需要预留出比他还大的位置即可,不会发生放进去后再次调整的问题。
func reconstructQueue(people [][]int) [][]int {
res := make([][]int, len(people))
sort.Slice(people, func(x,y int)bool{
if people[x][0] == people[y][0]{
return people[x][1] < people[y][1]
}
return people[x][0] < people[y][0]
})
for i := 0; i < len(people); i++{
count := 0
for j := 0; j < len(res) && j <= count + people[i][1]; j++{
if res[j] != nil && res[j][0] < people[i][0]{
count++
}
}
res[count + people[i][1]] = append( res[count + people[i][1]], people[i]...)
}
return res
}
452. 用最少数量的箭引爆气球
一个合并区间问题,用两个指针约束当前的最小公共区间,当不存在了的时候跳到下一个
func findMinArrowShots(points [][]int) int {
left := 0
right := math.MinInt64
count := 0
sort.Slice(points, func(i , j int)bool{
if points[i][0] == points[j][0]{
return points[i][1] < points[j][1]
}
return points[i][0] < points[j][0]
})
for i := 0; i < len(points); i++{
if right < points[i][0]{
count++
left = points[i][0]
right = points[i][1]
}else{
left = int(math.Max(float64(left), float64(points[i][0])))
right = int(math.Min(float64(right), float64(points[i][1])))
}
}
return count
}