LeetCode 406. Queue Reconstruction by Height
2017-12-08 17:06
351 查看
一、问题描述
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.
题意大致为:有一队伍,每个人用一个键值对来表示,键值对的第一个数表示这个人的身高,第二个数表示排在这个人前面的人且身高高于这个人的人数量;题目给定这些键值对,要求返回一个队列,使得该队列中人的排列顺序满足上述性质。
二、解题思路
一开始的思路是:先将人按身高从低到高排,如果身高相同则按第二个数从低到高排,然后每次从第一位开始遍历该数组,一旦找到符合要求的就加入到结果队列中并将其从原数组中删除,这样做是对结果队列的每一位逐一找到正确的人,缺点在于每向结果队列中加进一个人,都需要知道目前队列中的人比他高的有多少,才能决定这个人是不是合适加进去,实现起来比较麻烦。比较机智而且简洁的算法是:从身高高到低遍历每一个人,当每个人要加进队列的时候,由于比他先进入队列的人都比他高,所以他的键值对的第二个值是多少,他就插入到队列中的第几个,且由于后插入的数都比他小,就算插入位置在他之前,也不会影响到他
三、C++代码
class Solution { public: static bool cmp (pair<int, int> a , pair<int, int> b){ if(a.first == b.first ) return a.second < b.second ; return a.first > b.first ; } vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { sort(people.begin(), people.end(), cmp); vector<pair<int, int>> result; for(auto j : people) result.insert(result.begin() + j.second, j) ; return result; } };
相关文章推荐
- [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_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
- leetcode406. 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