思路:先对队列进行排序,k小的排前面,如果k相等,那么按照h小的排序;随后进行插入,每次插入元素 i ,检查前面有多少人升高比i的高,并对人数计数,对于相同的k,i应该按从小到大的顺序插入;
static bool cmp(vector<int> a, vector<int> b)
{
if (a[1] < b[1])
return true;
else if (a[1] == b[1])
{
return a[0] < b[0];
}
return false;
}
vector<vector<int>> reconstructQueue(vector<vector<int>> &people)
{
int len = people.size();
if (len < 2)
return people;
//排序
sort(people.begin(), people.end(), cmp);
vector<vector<int>> res;
res.push_back(people[0]);
//对剩下的元素进行插入
for (int i = 1; i < len; i++)
{
int cur_high = people[i][0], cur_order = people[i][1];
//如果k与前者相同,那么直接插入,因为k相同我是按升高从小到达排序的;
//如果身高相同, 并且k=前面的k+1,那么直接插入;
if (cur_order == res[i - 1][1] || (cur_high == res[i - 1][0] && cur_order == res[i - 1][1] + 1))
res.push_back(people[i]);
else
{
int count = 0;
int j = 0;
for (; j < i; j++)
{
if (res[j][0] >= cur_high)
{
count++;
}
if (count >= cur_order)
{
if (j + 1 < i && cur_high > res[j+1][0])
continue;
j += 1;
break;
}
}
res.insert(res.begin() + j, people[i]);
}
}
return res;
}