406. Queue Reconstruction by Height

这里写图片描述
方法一:

bool judge(const pair<int,int> &a, const pair<int ,int> &b) 
{
    if(a.second==b.second)
        return a.first>b.first;
    return a.second<b.second;
}
bool judge1(const pair<int,int> &a, const pair<int ,int> &b) 
{
        return a.first<b.first;
}
class Solution {
public:

    vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) 
    {
        vector<pair<int, int> >result;
        int i,j;
        if(0==people.size())
            return result;
        sort(people.begin(),people.end(),judge);//按人数从小到大排序,人数相同则按身高从高到矮排

        vector<pair<int,int> > ::iterator iter; 
        while(!people.empty())
        {
            iter=people.begin();
            if(iter->second==0)
            {
                result.push_back(pair<int,int>(iter->first,iter->second));//也可以写成result.push_back(make_pair(iter->first,iter->second));
                people.erase(iter);
            }
            else
                break;
        }
        sort(result.begin(),result.end(),judge1);//对于前面只有零个人的身高从矮到高排

        while(!people.empty())
        {
            iter=people.begin();
            int count=0;
            for(i=0;i<result.size();i++)
            {
                if(iter->second==count)
                {
                    result.push_back(pair<int,int>(0,0));
                    for(j=result.size();j>i;j--)
                    {
                        result[j].first=result[j-1].first;
                        result[j].second=result[j-1].second;
                    }
                    result[i].first=iter->first;
                    result[i].second=iter->second;
                    people.erase(iter);
                        break;
                }
                else if(result[i].first>=iter->first)
                    count++;
            }
            if(i==result.size())
            {
                result.push_back(pair<int,int>(iter->first,iter->second));
                people.erase(iter);
            }
        }
        return result;
    }
};

方法二:

class Solution {
public:
    static bool myComp(const pair<int, int> &a, const pair<int, int> &b)
    {
        if (a.first == b.first)
            return a.second < b.second;

        return a.first > b.first;
    }

    vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) {
        vector<pair<int, int> > ret;
        int n = people.size();
        if (n == 0)
            return ret;

        sort(people.begin(), people.end(), myComp);

        for (int i = 0; i < n; i++)
        {
            ret.insert(ret.begin() + people[i].second, people[i]);
        }

        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值