1. 程式人生 > >406 Queue Reconstruction by Height 根據身高重建隊列

406 Queue Reconstruction by Height 根據身高重建隊列

.com ems end cnblogs 輸出 rand desc 大於 ret

假設有打亂順序的一群人站成一個隊列。 每個人由一個整數對(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.com/problems/queue-reconstruction-by-height/description/

C++:

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        sort(people.begin(), people.end(), [](const pair<int,int> &a, const pair<int, int> &b){
            return a.first > b.first || (a.first == b.first && a.second < b.second);
        });
        for (int i = 0; i < people.size(); i++) 
        {
            auto p = people[i];
            if (p.second != i) 
            {
                people.erase(people.begin() + i);
                people.insert(people.begin() + p.second, p);
            }
        }
        return people;
    }
};

參考:https://www.cnblogs.com/grandyang/p/5928417.html

406 Queue Reconstruction by Height 根據身高重建隊列