- 452 用最少数量的箭引爆气球
- 来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons - 在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以纵坐标并不重要,因此只要知道开始和结束的横坐标就足够了。开始坐标总是小于结束坐标。
- 一支弓箭可以沿着 x 轴从不同点完全垂直地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足 xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。
- 给你一个数组 points ,其中 points [i] = [xstart,xend] ,返回引爆所有气球所必须射出的最小弓箭数。
示例 1:
输入:points = [[10,16],[2,8],[1,6],[7,12]]
输出:2
解释:对于该样例,x = 6 可以射爆 [2,8],[1,6] 两个气球,以及 x = 11 射爆另外两个气球
解题思路:【python3】 贪心算法 + 排序:将数组按右端从小到大排序,遍历数组,记录箭的数量count,若下一区间左侧小于等于当前区间cur右侧,说明1只箭可以贯穿这几个区间,当大于时,count加一,比较区间cur更新为当前遍历数组区间。
**Notes:**刚开始用自己写的排序方法,会超时= =。。。然后改用了函数list.sort(key=myFunction)
,key=myFunction自定义函数即排序的依据,此处根据数组的右侧边界排序,自定义函数返回右侧边界即可。
# python 3
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
if len(points)==0: return 0
dic = {}
# for i in range(len(points)):
# for j in range(i,len(points)):
# if points[i][1]>points[j][1]:
# points[i], points[j] = points[j], points[i]
# 获取列表的第二个元素
def takeSecond(elem):
return elem[1]
# 指定第二个元素排序
points.sort(key=takeSecond)
print(points)
count,cur = 1, 0
for i in range(1,len(points)):
if points[i][0] > points[cur][1]:
count += 1
cur = i
return count
Notes: 开始写【c++】时调用sort函数报错reference to non-static member function must be called!
,问题的原因:非静态成员函数指针和普通函数指针是有区别的。将cmp函数改为静态函数即可,其与普通指针没有区别。
// c++
class Solution {
public:
static bool cmp(vector<int>&a,vector<int>&b){
//按照二维数组第二列的大小对每个一维数组升序排序
return a[1]<b[1];
}
int findMinArrowShots(vector<vector<int>>& points) {
if (points.size()==0) return 0;
sort(points.begin(), points.end(),cmp);
//cout<<points<<endl;
int count =1, cur =0;
for (int i=1; i<points.size();++i){
if (points[cur][1] < points[i][0]){
cur = i;
++ count;
}
}
return count;
}
};