仿函数

仿函数(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 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值