[leetcode] 406. Queue Reconstruction by Height

https://leetcode.com/contest/6/problems/queue-reconstruction-by-height/

分析:每个表示成(a,b)的形式,其实找第一个,就是b为0,a最小的那一个,然后一次更新小于等于a的节点的序号b,就是b--,然后重复上面的过程。

我刚开始是按a排序,然后再按b排序,使用set来做,发现我还要修改set元素的值,发现不能修改,(这里还是对数据结构掌握的不透彻),左后使用vector来做,不断的进行排序,来维护顺序。代码写的有点乱,感觉还是紧张。

还有刚开始我在codeblock上调的,粘到leetcode,忘记修改node的比较函数,然后就罚时了。:(

 1   struct node {
 2     int h, n, v;
 3     bool operator<(const node & a) const {
 4         if(n == a.n) {
 5             return h < a.h;
 6         }
 7         return n < a.n;
 8     }
 9   };
10 class Solution {
11 public:
12    
13   vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
14         int n = people.size();
15         vector<pair<int, int> > res;
16         if(n < 2) return people;
17         set<node> se;
18         vector<node> v;
19         for (auto x : people) {
20             //se.insert({x.first, x.second, x.second});
21             v.push_back({x.first, x.second, x.second});
22         }
23         //cout << "asd" << endl;
24         sort(v.begin(), v.end());
25         for (int i = 0; i < n; i++) {
26             for (int j = 1; j < v.size(); j++) {
27                 if(v[j].h <= v[0].h) {
28                     v[j].n--;
29                 }
30             }
31             res.push_back({v[0].h, v[0].v });
32             v.erase(v.begin());
33             sort(v.begin(), v.end());
34         }
35         return res;
36     }
37 
38 };
原文地址:https://www.cnblogs.com/y119777/p/5905580.html