方法一:
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;
}
};