仿函数(functor)是通过重载()运算符模拟函数形式的类
- 仿函数不是函数,是个类
- 反函数重载了()运算符,使得它可以像函数一样调用
用最少的箭引爆气球
题目链接https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/
实例:
输入:points = [[10, 16], [2, 8], [1, 6], [7, 12]]
输出:2
解释:x=6,可以射爆[2, 8]和[1, 6]两个气球,x=11可以射爆另外两个气球
思路:按起始位置排序,处理最小末尾位置
#include <iostream>
#include <vector>
#incldue <algorithm>
using namespace std;
class comp
{
public:
bool operator()(const vector<int>& in1, const vector<int>& in2) const
{
vector<int> l1 = in1;
vector<int> l2 = in2;
return (in1[0] < in2[0]);
}
};
class solution
{
public:
int result(vector<vector<int>>& points)
{
if (points.empty())
{
return 0;
}
sort(points.begin(), points.end(), comp());//仿函数调用
int res = 1;
for (int i = 1; i < points.size(); i++)
{
if (points[i][0] > points[i-1][1])
{
res++;
}
else
{
points[i][1] = min(points[i][1], points[i-1][1]);
}
}
return res;
}
};
合并区间
给定一个区间集合,合并集合中所有重叠的区间
实例:
输入:points = [[5, 10], [6, 20], [36, 50], [49, 88]]
输出:[[5, 50], [36, 88]]
#include <iostream>
#include <vector>
#incldue <algorithm>
using namespace std;
class comp
{
public:
bool operator()(const vector<int>& in1, const vector<int>& in2) const
{
vector<int> l1 = in1;
vector<int> l2 = in2;
return (in1[0] < in2[0]);
}
};
class solutionMerge
{
public:
vector<vector<int>> merge(vector<vector<int>>& points)
{
vector<vector<int>> res;
if (points.empty())
{
return vector<vector<int>>();
}
sort(points.begin(), points.end(), comp());//仿函数调用
int startIndex = points[0][0];
for (int i = 1; i < points.size(); i++)
{
if (points[i][0] > points[i - 1][1])
{
vector<int> tmp;
tmp.push_back(startIndex);
tmp.push_back(points[i - 1][1]);
res.push_back(tmp);
startIndex = points[i][0];
}
else
{
points[i][1] = max(points[i][1], points[i - 1][1]);
if (i == points.size() - 1)
{
vector<int> tmp;
tmp.push_back(startIndex);
tmp.push_back(points[i][1]);
res.push_back(tmp);
}
}
}
return res;
}
};
具体讲解https://mp.weixin.qq.com/s/srOhZNLpQsgJ_TQmhEYjrg