目录
题目:
代码(首刷看解析 2024年2月17日):
class Solution {
private:
const static bool cmp(vector<int>& a, vector<int>& b) {
return a[0] < b[0];
}
public:
int findMinArrowShots(vector<vector<int>>& points) {
if (points.size() == 0) return 0;
/*将数组按首元素坐标升序排列*/
sort(points.begin(), points.end(), cmp);
int res = 1;
int index = 0;
for (int i = 0; i < points.size(); ++i) {
/*如果某个数组的首元素的坐标大于之前数组的最短末尾元素坐标,则箭增加*/
if (points[i][0] > points[index][1]) {
res++;
index = i;
}
if (points[i][1] <= points[index][1]) index = i;
}
return res;
}
};
代码(二刷自解 2024年6月16日 go)
func findMinArrowShots(points [][]int) int {
// 按照Xstart从小到大排序(若Xstart相等,按照Xend从小到大排序)
sort.Slice(points, func (a, b int) bool {
if (points[a][0] == points[b][0]) {
return points[a][1] < points[b][1]
}
return points[a][0] < points[b][0]
})
// 遍历slice,记录end
res := 0
end := math.MinInt64 // 定义最小值,避免第一个元素的头小于0
for _, value := range points {
if value[0] <= end {
end = min(end, value[1])
} else {
res++
end = value[1]
}
}
return res
}
func min(a,b int) int {
if a < b {
return a
}
return b
}