LeetCode Solutions
406. Queue Reconstruction by Height
Time: $O(n^2)$ Space: $O(n)$
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
vector<vector<int>> ans;
sort(begin(people), end(people), [](const auto& a, const auto& b) {
return a[0] == b[0] ? a[1] < b[1] : a[0] > b[0];
});
for (const vector<int>& p : people)
ans.insert(begin(ans) + p[1], p);
return ans;
}
};
class Solution {
public int[][] reconstructQueue(int[][] people) {
List<int[]> ans = new ArrayList<>();
Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);
for (final int[] p : people)
ans.add(p[1], p);
return ans.toArray(new int[ans.size()][]);
}
}