Leetcode-Algorithm-Greedy-406
- 題目:
- 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.
(假定一些人在一個隊列裏面隨機地站着。每一個人都是用一個整數對(h,k)來表示,h表示那個人的身高,k表示在他前面比他高或者身高跟他一樣的人的人的數量。設計一個算法重新構造這個隊列,使裏面的每個人都滿足條件。) - 注意:
- 假定表示人的整數對都是合理的。
例子:
輸入:[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]].
輸出:[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]].
題解:
方法:(貪心算法)
想法就是每遍歷到一個人,都能把它放到一個合適的位置,即之後每遍歷一個人都不會影響前一個人的選擇。要做到這一點,必須從身高最大的人開始遍歷,然後依次處理身高稍微小一點的。這樣就能保證處理的人不會影響到前面的人,就算後面的插的前面去了,也不會違反他要滿足的情況。所以算法包括以下兩個步驟:
①對人,也就是整數對按照身高由大到小的排序,當身高一樣時,第二個元素小的在前面,因爲第二個元素大的可能把身高跟他一樣的人也計算進去了。
②逐個遍歷排好序的隊列中的元素,把按照第二個元素的大小把人放到結果隊列相應位置。
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
auto comp = [](pair<int, int> &p1, pair<int, int> &p2) {
return (p1.first > p2.first) ||
(p1.first == p2.first && p1.second < p2.second);
};
sort(people.begin(), people.end(), comp);
vector<pair<int, int>> res;
for (auto &p : people) {
res.insert(res.begin()+p.second, p);
}
return res;
}
};
分析:
算法第一個步驟是排序,平均時間複雜度爲