Leetcode 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] = [h_i, k_i] represents the i-th person of height h_i with exactly k_i other people in front who have a height greater than or equal to h_i.
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] = [h_j, k_j] is the attributes of the j-th person in the queue (queue[j] is people[i] in the input).
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]]
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]]
[h, k] pairs in the input?
[h_i, k_i] pair is unique as per the problem constraints.people by height in descending order. For people with the same height, we sort them by their k value in ascending order.k value should be positioned first.people list and insert each person at the index equal to their k value in the result queue.k value since inserting at an index shifts elements to the right.people using a custom comparator:
k in ascending order.result list.result list at the index equal to their k value.Input: [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
#include <vector>
#include <algorithm>
class Solution {
public:
std::vector<std::vector<int>> reconstructQueue(std::vector<std::vector<int>>& people) {
// Sorting the people array
std::sort(people.begin(), people.end(),
[](const std::vector<int>& a, const std::vector<int>& b) {
return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]);
});
std::vector<std::vector<int>> result;
// Inserting each person into the result based on their k value
for (const auto& person : people) {
result.insert(result.begin() + person[1], person);
}
return result;
}
};
people array.Overall, the time complexity is (O(N^2)), which is efficient enough for the given constraint (1 <= people.length <= 2000).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?