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.
Example
Input: [[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]]
這道題給了我們一個隊列,隊列中的每個元素是一個 pair,分別為身高和前面身高不低於當前身高的人的個數,讓我們重新排列隊列,使得每個 pair 的第二個參數都滿足題意。首先來看一種超級簡潔的方法,給隊列先排個序,按照身高高的排前面,如果身高相同,則第二個數小的排前面。然后新建一個空的數組,遍歷之前排好序的數組,然后根據每個元素的第二個數字,將其插入到 res 數組中對應的位置,參見代碼如下:
解法一:
class Solution { public: vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { sort(people.begin(), people.end(), [](vector<int>& a, vector<int>& b) { return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]); }); vector<vector<int>> res; for (auto a : people) { res.insert(res.begin() + a[1], a); } return res; } };
上面那種方法是簡潔,但是用到了額外空間,我們來看一種不使用額外空間的解法,這種方法沒有使用 vector 自帶的 insert 或者 erase 函數,而是通過一個變量 cnt 和k的關系來將元素向前移動到正確位置,移動到方法是通過每次跟前面的元素交換位置,使用題目中給的例子來演示過程:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
排序后:
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
交換順序:
[[7,0], [6,1], [7,1], [5,0], [5,2], [4,4]]
[[5,0], [7,0], [6,1], [7,1], [5,2], [4,4]]
[[5,0], [7,0], [5,2], [6,1], [7,1], [4,4]]
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
解法二:
class Solution { public: vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { sort(people.begin(), people.end(), [](vector<int>& a, vector<int>& b) { return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]); }); for (int i = 1; i < people.size(); ++i) { int cnt = 0; for (int j = 0; j < i; ++j) { if (cnt == people[i][1]) { auto t = people[i]; for (int k = i - 1; k >= j; --k) { people[k + 1] = people[k]; } people[j] = t; break; } ++cnt; } } return people; } };
下面這種解法跟解法一很相似,只不過沒有使用額外空間,而是直接把位置不對的元素從原數組中刪除,直接加入到正確的位置上,參見代碼如下:
解法三:
class Solution { public: vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { sort(people.begin(), people.end(), [](vector<int>& a, vector<int>& b) { return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]); }); for (int i = 0; i < people.size(); i++) { auto p = people[i]; if (p[1] != i) { people.erase(people.begin() + i); people.insert(people.begin() + p[1], p); } } return people; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/406
類似題目:
Count of Smaller Numbers After Self
參考資料:
https://leetcode.com/problems/queue-reconstruction-by-height/
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/89348/6-lines-Concise-C%2B%2B