Queue Reconstruction by Height 题解
来源:互联网 发布:唐小僧 应用欺诈优化 编辑:程序博客网 时间:2024/05/16 08:02
Queue Reconstruction by Height题解
题目描述:
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k)
, where h
is the height of the person and k
is the number of people in front of this person who have a height greater than or equal to h
. Write an algorithm to reconstruct the queue.
链接:406. Queue Reconstruction by Height
Example
Input:[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]Output:[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
算法描述:
根据题意,我们将对 vector 中的 pair 进行规则排序,pair 中第一个数表示身高,第二个数表示在其之前有多少个人身高不低于他(我们用“排名”表示),第一步,我们先按照这样的思路进行一个初始排序:按照身高从高到低的顺序依次排列,如果两个人身高一样,比较他们的“排名”,“排名”小的在前。这样,我们就能得到初始序列:[ [7,0],[7,1],[6,1],[5,0],[5,2],[4,4] ]。
第二步,我们用这样的策略:创建结果 vector 为 new_queue, 并对初始初始序列的每个 pair 进行遍历,按照“排名”的值(表示每个 pair 的相对位置)在结果 new_queue 中进行插入。如:遍历到 [7,0] 时,“排序”为 0,将其插入到 0 的位置,此时 vector 为[[7,0]];之后遍历到 [7,1] 时,“排序”为 1 ,将其插入到 1 的位置,此时 vector 为[ [7,0],[7,1] ];当其遍历到[6,1]时,“排序”为 1,将其插入到 1 的位置,此时 vector 为[ [7,0],[6,1],[7,1] ];按照这样的方法即可完成。算法复杂度为O(n²) 。
代码:
class Solution {public: vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { vector<pair<int,int>> new_queue; auto method=[](pair<int,int> &p1, pair<int,int> &p2){ return p1.first>p2.first || p1.first==p2.first && p1.second<p2.second; }; sort(people.begin(),people.end(),method); for(auto &it : people){ new_queue.insert(new_queue.begin()+it.second,it); } return new_queue; }};
- Queue Reconstruction by Height 题解
- 题解:Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height 题解(C++)
- LeetCode#406 Queue Reconstruction by Height题解(C++版)
- leetcode406. Queue Reconstruction by Height
- 带你深入理解Android Handler机制
- Ajax
- 无线协议栈的优势
- 2017寒假ACM集训总结
- MPEG-2 TS学习(三)多媒体文件格式之TS
- Queue Reconstruction by Height 题解
- 装饰设计模式简析
- ubuntu12.04.4下安装python2.7.6
- Uboot Beaglebone Black Usb驱动分析
- Oracle常用诊断事件清单
- CF
- theano官方lstm代码解析(1)
- CMake学习
- Hibernate中配置二级缓存及查询缓存