LeetCode 406. Queue Reconstruction by Height (Medium)
来源:互联网 发布:系统格式化数据恢复 编辑:程序博客网 时间:2024/06/05 07:31
题目描述:
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]]
题目大意:有一个队列,每个队列中的人都有一个标识:1.身高 2.前面有多少个人比TA高。重排队列使新队列满足标识。
思路:先对输入队列进行排序,按如下规则1.身高越高排越前 2.身高相同,“比TA高的人“越少排越前。然后将排序后的元素插入到一个新数组中,位置为数组起始位置+比TA高的人的数量。
这个方法其实是网上的解题方法,我想了一下:越高的人排越前,使得后插入的元素必定小于等于先插入的元素,从头按条件2的顺序安排位置保证了元素的位置在本次插入一定使队列正确,即使后插入的元素插入到已经插入的元素的前面也不会影响队列的正确性。
c++代码:
class Solution {public: vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { vector<pair<int, int>> ans; sort(people.begin(), people.end(), cmp); for (int i = 0; i < people.size(); i++) { ans.insert(ans.begin() + people[i].second, people[i]); } return ans; } static bool cmp(const pair<int, int>& a, const pair<int, int>& b) { return a.first > b.first || (a.first == b.first && a.second < b.second); }};
阅读全文
0 0
- LeetCode 406. Queue Reconstruction by Height (Medium)
- Leetcode 406. Queue Reconstruction by Height[Medium]
- LeetCode解题报告 406. Queue Reconstruction by Height [medium]
- 406. Queue Reconstruction by Height (Medium)
- 406. Queue Reconstruction by Height Difficulty : Medium
- [Medium]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
- 网络爬虫-验证码登陆
- Python 安装pip
- 网络爬虫-使用Cookie登陆
- 如何制作swift framework
- 响应式和自适应的区别
- LeetCode 406. Queue Reconstruction by Height (Medium)
- hadoop是大数据火爆的助燃剂
- leetcode 117. Populating Next Right Pointers in Each Node II BFS广度优先遍历
- 简单理解观察者模式
- [PDF]AI 机器学习 深度学习 经典书籍汇总下载
- AppSettings 的使用
- Open Refine能学到什么
- 从程序员到CTO的Java技术路线图
- Python学习笔记——文件操作