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

  • 这道题目的关键是:只有身高大于等于自身的人,对于K值才有影响。假设A的身高为h,身高大于等于h的人的站位会影响A的K值,而身高小于h的人无论是站在A的前面抑或是后面,对于A的K值都是没有影响的。但是A的站位却会影响比A身高矮的人的K值,所以唯有先确定A的站位,才可确定身高小于A的人的站位,所以初步猜想是将所有人按照身高从高到低排序,依次插入到一个新的队列中去,插入的位置就是K值的大小。
  • 第二个要考虑的问题就是身高相同的人,但是K值不同,显然K值越大的人站位越靠后,因为对于H相同的人,站位靠后的K值至少比前面的大1。所以要先插入K值较小的人。因此得出这样的排序规则。
    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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 声明:作者翻译论文仅为学习,如有侵权请...
    SnailTyan阅读 6,745评论 0 4
  • 我们生活中,总会有各种各样的新店铺开张。因此,也会有许多的就店铺关门。我们总是这样评价:这家店铺不如以前了。曾经我...
    我是狐狸一只阅读 245评论 0 0
  • 夜晚的厨房发出乒乒乓乓的碰撞声,一下,两下,三下,四下,到第五下的时候戛然而止,迎来的是死一般的寂静。 “你有没有...
    天天杨阅读 280评论 0 0
  • 01 全员离职的我们……我……们…… 就在今晚11点多,之前广告公司的同事微信我: 我,终于,也还是走了,心太累了...
    遇见逗逗阅读 474评论 0 1