題目描述
假設有打亂順序的一群人站成一個隊列。 每個人由一個整數對(h, k)表示,其中h是這個人的身高,k是排在這個人前面且身高大於或等於h的人數。 編寫一個算法來重建這個隊列。
注意:
總人數少於1100人。
示例:
輸入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
輸出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
題目鏈接: https://leetcode-cn.com/problems/queue-reconstruction-by-height/
思路
將整數對 (h, k) 按照 h 降序排序,如果 h 相同,則按照 k 升序排序。排序完畢后,令結果數組為 ans,從頭開始遍歷數組,將數組中的每個元素插入到 ans[k] 的位置。代碼如下:
class Solution {
public:
static bool cmp(const vector<int>& a, const vector<int>& b){
if(a[0]!=b[0]) return a[0]>b[0]; // 按照 h 降序排序
else return a[1]<b[1]; // 按照 k 升序排序
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(), people.end(), cmp);
vector<vector<int>> ans;
for(auto v:people){
ans.insert(ans.begin()+v[1], v);
}
return ans;
}
};
- 時間復雜度:O(n^2)
- 空間復雜度:O(n)