• LeetCode406. Queue Reconstruction by Height Add to List


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

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    bool compare(const pair<int, int>& p1, const pair<int, int>& p2)
    {
        return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second);
    }
    
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        sort(people.begin(), people.end(), compare);
        //按照高度h进行降序排序,如果高度相同就按高于的人数升序排序
        //排序后结果[7,0] [7,1] [6,1] [5,0] [5,2] [4,4]
        //每一pair都小于等于前面的每一个pair
        vector<pair<int, int>> res;
        for (auto& p : people)
            res.insert(res.begin() + p.second, p);
        //根据前面有高于的数目插入相应位置
        //如[6,1]插入到位置1,前面只有[7,0],所以满足了[6,1]要求
        //[5,0]插入到位置0,满足[5,0]要求
        //[5,2]插入到位置2,前面有[5,0] [7,0],满足要求
        //……
        return res;
    }
    
    
    //下面是测试案例
    int main()
    {
    
        vector<pair<int, int> > pp;
        pp.push_back(make_pair<int,int>(7,0));
        pp.push_back(make_pair<int,int>(4,4));
        pp.push_back(make_pair<int,int>(7,1));
        pp.push_back(make_pair<int,int>(5,0));
        pp.push_back(make_pair<int,int>(6,1));
        pp.push_back(make_pair<int,int>(5,2));
    
        for(auto iter=pp.begin();iter!=pp.end();iter++)
        {
            cout<<"["<<iter->first<<","<<iter->second<<"]"<<" ";
        }
        vector<pair<int, int>> res = reconstructQueue(pp);
        cout << endl << "-------------------------------" << endl;
        for(auto iter=res.begin();iter!=res.end();iter++)
        {
            cout<<"["<<iter->first<<","<<iter->second<<"]"<<" ";
        }
        cout << endl;
        return 0;
    }
    

    输出:

    [7,0] [4,4] [7,1] [5,0] [6,1] [5,2]

    [5,0] [7,0] [5,2] [6,1] [4,4] [7,1]

  • 相关阅读:
    Windows7下安装golang语言开发环境和revel框架
    Go实战--通过gin-gonic框架搭建restful api服务(github.com/gin-gonic/gin)
    Go语言web框架 gin
    最好的6个Go语言Web框架
    mac:Go安装和配置+GoLand安装和使用之完整教程
    Goland软件使用教程(二)
    Goland软件使用教程(一)
    http_load常见问题及解决方案
    定义类和接口
    关于 xftp 上传文件时,仅仅是上传了0字节的问题
  • 原文地址:https://www.cnblogs.com/yangjiannr/p/7391350.html
Copyright © 2020-2023  润新知