题目描述
406. Queue Reconstruction by Height
You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.
Reconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).
Example 1:
Input: people = [[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]]
Explanation:
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.Example 2:
Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]
Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]1 <= people.length <= 20000 <= hi <= 10^60 <= ki < people.length- It is guaranteed that the queue can be reconstructed.
解题思路
题目描述:整数对 (h, k) 表示,其中 h 是这个人的身高,k 是排在这个人前面且身高大于或等于 h 的人数。
渔(套路):一般这种数对,还涉及排序的,根据第一个元素正向排序,根据第二个元素反向排序,或者根据第一个元素反向排序,根据第二个元素正向排序,往往能够简化解题过程。
在本题目中,我首先对数对进行排序,按照数对的元素 1 降序排序,按照数对的元素 2 升序排序。
按照元素 1 进行降序排序,对于每个元素,在其之前的元素的个数,就是大于等于他的元素的数量。这样的目的是,保证每次插入排序的时候,一定能保证结果集res数组里所有的数都比当前待插入的数大!这样只用考虑k者一个因子即可。
按照第二个元素正向排序,我们希望 k 大的尽量在后面,减少插入操作的次数。









代码
for 循环实现,额外 res 数组空间存储
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(),people.end(),[](vector<int>&a,vector<int>&b){
if(a[0]==b[0]) return a[1]<b[1];
return a[0]>b[0];
});
vector<vector<int>> res;
for(int i = 0;i<people.size();++i){
vector<int> p = people[i];
res.insert(res.begin()+p[1],p);
}
return res;
}
};while 循环实现,原地改变
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people = sorted(people, key = lambda x: (-x[0], x[1]))
i = 0
while i < len(people):
if i > people[i][1]:
people.insert(people[i][1], people[i])
people.pop(i+1)
i += 1
return people