LeetCode406. Queue Reconstruction by Height Add to List
2017-03-31 16:40
351 查看
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]]
#include <iostream> #include <vector> using namespace std; bool compare(const pair<int, int>& p1, const 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) { sort(people.begin(), people.end(), compare); //按照高度h进行降序排序,如果高度相同就按高于的人数升序排序 //排序后结果[7,0] [7,1] [6,1] [5,0] [5,2] [4,4] //每一pair都小于等于前面的每一个pair vector<pair<int, int>> res; for (auto& p : people) res.insert(res.begin() + p.second, p); //根据前面有高于的数目插入相应位置 //如[6,1]插入到位置1,前面只有[7,0],所以满足了[6,1]要求 //[5,0]插入到位置0,满足[5,0]要求 //[5,2]插入到位置2,前面有[5,0] [7,0],满足要求 //…… return res; } //下面是测试案例 int main() { vector<pair<int, int> > pp; pp.push_back(make_pair<int,int>(7,0)); pp.push_back(make_pair<int,int>(4,4)); pp.push_back(make_pair<int,int>(7,1)); pp.push_back(make_pair<int,int>(5,0)); pp.push_back(make_pair<int,int>(6,1)); pp.push_back(make_pair<int,int>(5,2)); for(auto iter=pp.begin();iter!=pp.end();iter++) { cout<<"["<<iter->first<<","<<iter->second<<"]"<<" "; } vector<pair<int, int>> res = reconstructQueue(pp); cout << endl << "-------------------------------" << endl; for(auto iter=res.begin();iter!=res.end();iter++) { cout<<"["<<iter->first<<","<<iter->second<<"]"<<" "; } cout << endl; return 0; }
输出:
[7,0] [4,4] [7,1] [5,0] [6,1] [5,2]
[5,0] [7,0] [5,2] [6,1] [4,4] [7,1]相关文章推荐
- leetcode406. Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height
- LeetCode406. Queue Reconstruction by Height
- Leetcode解题报告:406. Queue Reconstruction by Height
- 【LeetCode】 406. Queue Reconstruction by Height
- leetcode_middle_2_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
- LeetCode406. 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