STL-priority_queue

priority_queue

priority_queue<int, vector<int>, greater<int>> pq;

使小的数字优先级变高,默认大的优先级高。

215. 数组中的第K个最大元素

. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=O83Ahttps://leetcode.cn/problems/kth-largest-element-in-an-array/description/

 int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int, vector<int>, greater<int>> pq;
        int i = 0;
        for (; i < k; i++)
            pq.push(nums[i]);
        for (; i < nums.size(); ++i) {
            if (nums[i] > pq.top()) {
                pq.pop();
                pq.push(nums[i]);
            }
        }
        return pq.top();
    }

priority_queue 

priority_queue的底层结构是一个堆。

template<class T,class Container=vector<T>>
class priority_queue
{
public:
	void AdjustUp(int child)
	{
		int parent = (child - 1) / 2;
		while (child > 0)
		{
			if (_con[parent] < _con[child])
			{
				swap(_con[parent], _con[child]);
				child = parent;
				parent = (child - 1) / 2;
			}
			else
				break;
		}
	}
	void push(const T& x)
	{
		//O(logN)
		_con.push_back(x);
		AdjustUp(_con.size() - 1);
	}
	void pop()
	{
		swap(_con[0], _con[_con.size()]);
		_con.pop_back();
		AdjustDown(0);
	}
	T& top();
	size_t size()
	{
		return _con.size();
	}
	bool empty()
	{
		return _con.empty();
	}
private:
	Container _con;
};

adjust_down/pop

void AdjustDown(int root)
{
	int parent = root, child = parent * 2 + 1;
	while (child < _con.size)
	{
		//的确保有孩子存在
		if (child+1<_con.size()&&_con[child + 1] > _con[child]) child++;
		if (_con[parent] > _con[child])
		{
			swap(_con[parent], _con[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
			break;
	}
}
void pop()
{
	swap(_con[0], _con[_con.size()]);
	_con.pop_back();
	AdjustDown(0);
}

仿函数   

仿函数对象可以向函数一样去使用。

namespace test
{
	//仿函数   函数对象
	template<class T>
	struct less
	{
		bool operator()(const T& x1, const T& x2)
		{
			return x1 < x2;
		}
	};
}

sort默认排升序 <  及less

排降序

greater<int> gt;
sort(v.begin(),v.end(),greater<int>());
sort(v.begin(),v.end(),greater<int>());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值