 
- 思路
Xstart ≤ X ≤ Xend,则该气球会被引爆,求使得所有气球全部被引爆,所需的弓箭的最小数量。 这是一个典型的贪心算法,每支箭都要尽可能多的射中气球。能看到points数组是有两个维度的,因此要一个一个维度的来确定,并让有重合的数组放在一起,以便计算需要的箭。 先对points数组进行排序,就按照第一个维度进行排序,从小到大,若相等则第二个维度大的在前面。然后进行比较,记录cover为前一个的第二个坐标,若后一个的第一个坐标小于等于它则可以一起爆,否则,更新cover为后一个的第二个坐标,?+1。
func findMinArrowShots(points [][]int) int {
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]
})
count, cover := 1, points[0][1]
for i := 1; i < len(points); i++ {
if points[i][0] > cover {
cover = points[i][1]
count++
}
}
return count
}

func findMinArrowShots(points [][]int) int {
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]
})
count, cover := 1, points[0][1]
for i := 1; i < len(points); i++ {
if points[i][0] > cover {
cover = points[i][1]
count++
} else {
if points[i][1] < cover {
cover = points[i][1]
}
}
}
return count
}

|