LeetCode 中的某些数据结构写法

""

因为做题的时候总是会搞不清楚如何定义和使用一些有用的数据结构

所以在此做一个记录 orz

""

 

1. 优先队列

使用大小顶堆来实现:

主要操作 : top(),empty(),push(),pop(),size()

 

最大堆 : priority_queue <int,vector<int>,less<int> > p;

最小堆 : priority_queue <int,vector<int>,greater<int> > p;  

(cmp表示优先级,把它看成一个数组,优先级高的在前面,pop的是数组最后的元素)

 

 

对于cmp的写法

 

若写在外面,用struct写 (Pll -> pair 类型)

struct cmp { 
     bool operator ()(PII &a,PII &b) { 
         return a.first<b.first;//最小值优先 
     } 
}; 

priority_queue <pair<int,int>,vector<pair<int,int> >,cmp> p;

 

若写在函数里面,用auto cmp来写

auto cmp = [](PII &a,PII &b){return a.second<b.second;};

priority_queue<PII, vector<PII>, decltype(cmp) > save(cmp); 

 

2021 03.14 补充 (因为周赛的时候用 vector 作为元素超时)

题目链接 : 5703. 最大平均通过率  

https://leetcode-cn.com/problems/maximum-average-pass-ratio/

struct Node {
    double v;
    int a,b;
    bool operator< (const Node& t) const {
        return v < t.v;
    }// < 用于在优先队列中的比较的逻辑,即 v 大的优先弹出
};// 用于表示原来的 vector 用于存储的数据
priority_queue<Node> p;// 默认是大根堆
for(auto& i : c) {
    int b = i[0];
    int a = i[1];
    res += (double)b / a;
    p.push({(a - b) / (a  *(a + 1.0)),a,b});// 自己会创建一个结构体并赋值
}

 

 

 

 

2. map,set 的遍历

利用auto 来遍历

auto:
map<int,int> mp;
for(int i =0;i<5;i++) mp[i] = i+1;
for(auto& it: mp) cout<<it.first<<" "<<it.second<<endl;

非auto正向遍历
map<int, string>::iterator   iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
    cout<<iter->first<<" "<<iter->second<<endl;

非auto(反向遍历):
map<int, string>::reverse_iterator   iter;
for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)
    cout<<iter->first<<" "<<iter->second<<endl;


set<int> st;
for(int i =0;i<5;i++) st.insert(i);
for(auto& i : st) cout<<i<<endl;

 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值