LeetCode OJ 406. Queue Reconstruction by Height
来源:互联网 发布:西安程序麻将机软件 编辑:程序博客网 时间:2024/06/05 14:23
LeetCode OJ 406. Queue Reconstruction by Height
Description
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]]
解题思路
这个题目的解题方法一开始比较难想到。但是有了想法做起来就很简单。
队列中的元素(h,k)表示在这个元素前比h大的元素有k个。题意是要把这样的元素组成的队列排序。首先把元素排序:按照h的降序排列,h相等时,按照k的升序排列。然后我们再一个个把元素插入到结果队列中。插入的方法是:插入到当前队列下标为k的位置。因为我们之前插入的都是比这个元素的h值大的元素,因此当前元素的h值就是队列中所剩下未插入结果队列的h值最大的元素了。而且k值是升序排列的,保证了结果插入的过程中不会越界。
eg.
题目中所给的输入进行排序后
Input: [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
结果Result首先插入第一个元素[7,0]:
Result: [[7,0]]
插入第二个元素[7,1],在Result中下标为1的位置,即偏移量为1:
Result: [[7,0], [7,1]]
插入第三个元素[6,1]:
Result: [[7,0], [6,1], [7,1]]
插入第四个元素[5,0]:
Result: [[5,0], [7,0], [6,1], [7,1]]
插入第五个元素[5,2]:
Result: [[5,0], [7,0], [5,2], [6,1], [7,1]]
插入第六个元素[4,4]:
Result: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
Note:
std::sort函数是全局的,如果第三个参数cmp不是静态成员函数或者全局函数,运行都会报错。非静态函数是依赖于具体对象的,因此调用sort函数时,只能调用不依赖于对象的静态函数cmp。
代码
个人github代码链接
class Solution {public: static bool cmp(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>> ans; sort(people.begin(), people.end(), cmp); for(auto p:people){ ans.insert(ans.begin() + p.second, p); } return ans; }};
- LeetCode OJ 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
- [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
- PDO事务回滚
- 最大连续数列的和
- tomcat 性能优化
- 手动实现单链表和循环链表
- Linux命令长选项和短选项区别
- LeetCode OJ 406. Queue Reconstruction by Height
- C语言指针导学(6)——使用指针时的“陷阱”
- 蓝桥杯 ADV-89 算法提高 输出九九乘法表
- TensorFlow 新手入门
- 使用dd命令新增交换分区
- Criter涉及到的查询
- 深入理解HTTP协议、HTTP协议原理分析
- JavaScript 自执行函数(闭包)
- struct accessor实现for c