Queue Reconstruction by Height解題報告

Description:

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]]

Link:

https://leetcode.com/problems/queue-reconstruction-by-height/description/

解題方法:

矮個子對于高個子在這道題中并沒有什么意義,所以我們先處理最高的,然后矮個子可以根據(jù)第二個值往其中插入,從而不會影響高個子。對于相同高的人,我們優(yōu)先處理第二個值小的,因為相同高度的人可以互相影響。

  • 所以先把數(shù)組按照身高將序,當(dāng)身高相同第二個值升序排列。
  • 再遍歷一遍數(shù)組, 把每個人插到與其第二個值相對應(yīng)的位置即可。

Time Complexity:

O(nlogn)

完整代碼:

vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) 
    {
        sort(people.begin(), people.end(), [](pair<int, int> a, pair<int, int> b) {
            if(a.first > b.first)
                return true;
            if(a.first == b.first)
                return a.second < b.second;
            return false;
        });
        vector<pair<int, int>> result;
        for(auto a: people)
            result.insert(result.begin() + a.second, a);
        return result;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容