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]]
解法一:
将pair对按照h为首要排序因素,k为次要排序因素进行排序(利用set的自动排序)得到I以下序列,
4,4 5,0 5,2 6,1 7,0 7,1
现在有1 2 3 4 5 6个空位没有把people放进去
因为身高为4是最低的,所以无论哪一个人出来,其身高都是大于等于他的,所以4,4应该放在剩余位置中的第5个位置,此时剩下的位置有1,2,3,4,6
现在身高5是最低的,无论哪一个人出来,其身高都是大于等于5的,而且5,0这个人前面没有一个人的身法大于等于他,所以他应该是剩余位置中的第一个,此时剩下的位置为2,3,4,6
现在身高5是最低的,无论哪一个人出来,其身高都是大于等于5的,但是现在在队伍中排好位置的人中没有比5,2高的,只有一个和5,2身高相同的,所以讲5,2应该放在剩余位置中的第2个,此时剩下的位置为2,4,6
现在身高6是最低的,无论哪一个人出来,身高都是大于等于6的,6,1前面只有一个人身高高于他,所以6,1应该放在剩余位置中国的第2个
........
同上,最终得到序列[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]
利用set的自动排序得到如下代码:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people)
{
//the set of position we have not used.
set<int> left_positions;
//the set of people that has been sorted.
set<pair<int, int>> left_people;
//the right positions people should stand.
vector<pair<int, int>> people_positions(people.size());
for(int i = 0; i < people.size(); i++)left_positions.insert(i);
for(int i = 0; i < people.size(); i++)left_people.insert(people[i]);
for(set<pair<int, int>>::iterator itr = left_people.begin(); itr != left_people.end(); itr++)
{
people_positions[*(left_positions.begin() + (*itr).second)] = *itr;
left_positions.erase(left_positions.begin() + (*itr).second);
}
}
解法二:
因为只有身高大于等于自己的人,排在自己前面,自己的k才会变化,将排序的依据变为代码中的mygreater,此时得到的排序后的序列为[7,0] [7,1] [6,1] [5,0] [5,2] [4,4]
因为7,0的身高是最高的,而且前面有0个人身高大于等于7,所以将7,0先放到队列中的第一位
因为现在7,1的身高是最高的,其前面有一个人身高大于等于7,现在在队伍中只有一个人,且队伍中的那个人身高肯定大于等于7(排序依据),所以将7,1放到队列中的第二位
现在6,1身高是最高,其前面只有一个人身高大于等于6,但是现在队伍中每一个人身高都是大于等于6的,所以要将6,1放到队伍中的第二位
现在5,0身高最高,但是他的前面没有人身高比他高,但是现在队列中每一个人的身高都是大于等于5的,所以要架构5,0放到队伍中的第一位。
.....
最终得到队伍顺序:[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]
以下是实现的代码
static bool mygreater(pair<int, int> &a, pair<int, int> &b)
{
return a.first > b.first || (a.first == b.first && a.second < b.second);
}
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people)
{
sort(people.begin(), people.end(), mygreater);
vector<pair<int, int>> result;
for (auto p : people)result.insert(result.begin() + p.second, p);
return result;
}