LeetCode -- Queue Reconstruction by Height

Difficulty: Medium
Problem Link: https://leetcode.com/problems/queue-reconstruction-by-height/

Problem

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]]
Tag: Greedy

Explanation

  • 這道題目的關(guān)鍵是:只有身高大于等于自身的人,對于K值才有影響。假設(shè)A的身高為h,身高大于等于h的人的站位會影響A的K值,而身高小于h的人無論是站在A的前面抑或是后面,對于A的K值都是沒有影響的。但是A的站位卻會影響比A身高矮的人的K值,所以唯有先確定A的站位,才可確定身高小于A的人的站位,所以初步猜想是將所有人按照身高從高到低排序,依次插入到一個新的隊列中去,插入的位置就是K值的大小。
  • 第二個要考慮的問題就是身高相同的人,但是K值不同,顯然K值越大的人站位越靠后,因為對于H相同的人,站位靠后的K值至少比前面的大1。所以要先插入K值較小的人。因此得出這樣的排序規(guī)則。
    auto comp = [](const pair<int, int>& x, const pair<int, int>& y) { return (x.first > y.first || (x.first == y.first && x.second < y.second)); };

cpp solution

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        auto comp = [](const pair<int, int>& x, const pair<int, int>& y) {
            return (x.first > y.first || (x.first == y.first && x.second < y.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;
    }
};
最后編輯于
?著作權(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)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,931評論 0 33
  • 文章作者:Tyan博客:noahsnail.com | CSDN | 簡書 聲明:作者翻譯論文僅為學(xué)習(xí),如有侵權(quán)請...
    SnailTyan閱讀 6,907評論 0 4
  • 我們生活中,總會有各種各樣的新店鋪開張。因此,也會有許多的就店鋪關(guān)門。我們總是這樣評價:這家店鋪不如以前了。曾經(jīng)我...
    我是狐貍一只閱讀 267評論 0 0
  • 夜晚的廚房發(fā)出乒乒乓乓的碰撞聲,一下,兩下,三下,四下,到第五下的時候戛然而止,迎來的是死一般的寂靜。 “你有沒有...
    天天楊閱讀 316評論 0 0
  • 01 全員離職的我們……我……們…… 就在今晚11點多,之前廣告公司的同事微信我: 我,終于,也還是走了,心太累了...
    遇見逗逗閱讀 526評論 0 1

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