题解:Queue Reconstruction by Height
来源:互联网 发布:创世纪 知乎 编辑:程序博客网 时间:2024/05/16 05:57
题目如下:
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.
Note:
The number of people is less than 1,100.
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]]
解题思路方面,先按照由高到低的高度排序(如果高度一样,则k较小者排前),随后依次根据k的值(因为前面有的人数算是比较决定性的条件)选择插入的位置把排序后的向量每一个元素放进新的向量,最后返回该向量。
代码如下:
class Solution {public:static bool cmp(const pair<int, int> &a, const pair<int, int> &b) { if (a.first == b.first) return a.second < b.second; return a.first > b.first; } vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) { vector<pair<int, int> > result; sort(people.begin(), people.end(), cmp); for (int i = 0; i < people.size(); i++) { result.insert(result.begin() + people[i].second, people[i]); } return result; }};
阅读全文
0 0
- 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
- Python安装zlib模块
- windows系统禁止屏幕旋转快捷键
- bzoj 1061: [Noi2008]志愿者招募 单纯形
- JS
- 关于‘Starting Tomcat v7.0 Server at localhost’ has encountered a problem问题
- 题解:Queue Reconstruction by Height
- BeanFactory和ApplicationContext容器的bean后置处理器方式的不同
- 设计模式三之备忘录模式
- String
- 用grunt搭建自动化的web前端开发环境实战教程(详细步骤)
- spring配置文件报错
- 今天做到一道面试题:JVM的工作原理
- [Hive]那些年踩过的Hive坑
- ios 蓝牙开发,蓝牙应用