leetcode406

本文介绍了一种使用STL实现的队列重构算法,通过贪婪策略对pair元素进行排序,以解决特定问题。文章详细阐述了排序逻辑及其实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

并不是太简单,还是有点难度,这是stl的胜利。

本题采用greedy的思路,对于pair(h,k)。首先确定优先顺序:按照k从小到大的顺序排序;当k相同时,按照h从小到大排序。

首先 static bool cmp函数用于sort内使用,必须加上static,不然会出错。

std::sort(people.begin(),people.end(),cmp)对people排序。

distance函数可以返回正值或负值,根据情况而定,就是返回distance(begin,end)——-(end-begin).

itOld=result.insert(it,people[i]);返回插入后的地址。

每次操作前都需要比较一番插入前后的地址。

class Solution {
public:

    static bool cmp( pair<int,int>& a,  pair<int,int>& b)
    {
        if(a.second<b.second)
            return true;
        else if(a.second==b.second&&a.first<b.first)
            return true;
        else
            return false;
    }

    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        if(people.size()==0)
            return people;
        else
        {
            std::sort(people.begin(),people.end(),cmp);

            vector<pair<int, int>> result;
            result.push_back(people[0]);
            vector<pair<int, int>>::iterator it=result.begin();
            vector<pair<int, int>>::iterator itOld=result.begin();

            for(int i=1;i<people.size();i++)
            {
                int num=people[i].first;
                int time=people[i].second;

                int j=0;
                while(time!=0)
                {
                    if(result[j].first>=num)
                        time--;
                    j++;
                }

                it=result.begin()+j;
                if(people[i-1].second==people[i].second)
                {
                    if(distance(itOld,it)<=0)
                        it=itOld+1;
                }
                itOld=result.insert(it,people[i]);
            }
            return result;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值