priority_queue
priority_queue<int, vector<int>, greater<int>> pq;
使小的数字优先级变高,默认大的优先级高。
215. 数组中的第K个最大元素
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>());