406. Queue Reconstruction by Height
2017-05-18 15:06
295 查看
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。
E.g.
input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
step 1: [[7,0], [7,1]]
step 2: [[7,0], [6,1], [7,1]]
step 3: [[[5,0], [7,0], [5,2], [6,1], [7,1]]
step 4: [[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
所以,我们先按高到矮排序,身高相同则按k从小到大排序,之后一个个按k插入队列。
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个人的身高大于等于他的身高h。注意到,每次选身高最高的几个放入队列,因为他们比队列中的人都矮,所以不会破坏队列的性质,每个人放入序列的序号就等于k。
E.g.
input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
step 1: [[7,0], [7,1]]
step 2: [[7,0], [6,1], [7,1]]
step 3: [[[5,0], [7,0], [5,2], [6,1], [7,1]]
step 4: [[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
所以,我们先按高到矮排序,身高相同则按k从小到大排序,之后一个个按k插入队列。
class Solution { public: vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { //排序 sort(people.begin(), people.end(), [](const pair<int, int>& a, const pair<int, int>& b){ return a.first > b.first || (a.first == b.first && a.second < b.second); }); vector<pair<int, int>> ans; for(int i = 0; i < people.size(); i++){ ans.insert(ans.begin()+people[i].second, people[i]); } return ans; } };
相关文章推荐
- leetcode 406. Queue Reconstruction by Height
- [leetcode] 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- LeetCode笔记:406. Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height
- 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
- 406. Queue Reconstruction by Height(根据身高重排队列)
- 【leetcode】【M】406. Queue Reconstruction by Height【95】
- LeetCode 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height
- 【LeetCode】406.Queue Reconstruction by Height(Medium)解题报告
- [leetcode]406. Queue Reconstruction by Height
- 406. Queue Reconstruction by Height