Leetcode 406. Queue Reconstruction by Height
来源:互联网 发布:大四迷茫 知乎 编辑:程序博客网 时间:2024/06/05 12:53
Leetcode 406. Queue Reconstruction by Height
source url
题目描述
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.
输入:
输出:排序后的队伍
如:
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]]
思路1.
先对输入的序列对进行排序,首先根据高度排序,高度大的在前面;其次,当高度相同时,k小的在前。上述排序过后结果为:[[7,0],[7,1],[6,1],[5,0],[5,2],[4,4]]。随后,组成序列。基本思路是,大的数字先插入,插入位置为k。这样,能保证在插入第(i,k)时,已有序列本身都>=i,这是插到第k个位置是合理的。这种贪心策略每一步都是合理的。
代码
class Solution {public: static bool comp(pair<int, int>& p1, pair<int, int>& p2){ return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second); } vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { vector<pair<int, int>> res; sort(people.begin(), people.end(), this->comp); for (int i =0;i<people.size();i++) { pair<int, int>& p = people[i]; res.insert(res.begin() + p.second, p);} return res; }};
0 0
- LeetCode—406. Queue Reconstruction by Height
- [LeetCode]406.Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height
- [LeetCode] 406. Queue Reconstruction by Height
- Leetcode 406. Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height
- LeetCode笔记:406. Queue Reconstruction by Height
- 【LeetCode】 406. Queue Reconstruction by Height
- [leetcode]406. Queue Reconstruction by Height
- [Leetcode] 406. Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height
- Leetcode 406. Queue Reconstruction by Height
- [LeetCode]406. Queue Reconstruction by Height
- Leetcode-406. Queue Reconstruction by Height
- LeetCode OJ 406. Queue Reconstruction by Height
- 【LeetCode】406. Queue Reconstruction by Height
- Leetcode 406. Queue Reconstruction by Height
- 【leetcode】406. Queue Reconstruction by Height
- 基于Unity3D云人脸监测技术
- 最快捷的android eclipse转as
- Java语言基本语法(一)
- iOS随笔_网络(Socket/MQTT)
- linux基础命令学习之一-ls
- Leetcode 406. Queue Reconstruction by Height
- linux之stat命令
- Sqoop 的安装
- Android Studio资源自动清理工具
- Linux 万能的android.rules文件 解决 adb devices no permissions
- RCF—用于C++的进程间通讯(1)
- 【OpenCV入门教程之十一】 形态学图像处理(二):开运算、闭运算、形态学梯度、顶帽、黑帽
- RCF—用于C++的进程间通讯(2)
- JavaSE day02笔记