题目:
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers
(h, k)
, whereh
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 than1,100
.
ExampleInput: [[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]]
解释:
1.把人从高到低排序,而且按照k增长的顺序,需要自己写sort()函数,需要用到lambda
2.如果高度一样,那么按照k值从小到大排序。
排完序后可以注意到这样一个事实:如果先处理身高最高的,那他们的k值就是他们所应该在的位置——因为已经没有比他们更高的了,之后如果再处理比他低的,不管中间插入多少个,都不影响结果,因为中间无论有多少个比他低的都不会改变他的k值。
所以我们从高度从高到低按照k值的位置一直插入到答案中即可。
python代码:
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people.sort(key=lambda(h,k):(-h,k))
result=[]
for p in people:
result.insert(p[1],p)
return result
c++ 代码:
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
/*
auto comp = [](const pair<int, int>& p1, const pair<int, int>& p2)
{ return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second); };
*/
sort(people.begin(), people.end(), comp);
vector<pair<int, int>> res;
for (auto& p : people)
res.insert(res.begin() + p.second, p);
return res;
}
static bool comp(const pair<int, int>& p1, const pair<int, int>& p2)
{
return (p1.first>p2.first) ||(p1.first==p2.first && p1.second<p2.second);
}
};
总结:
c++实现二维数组的排序比较麻烦,其实也是需要自己写比较函数,但是比python要麻烦一点。
c++中用[]
开头的是lambda表达式。如果不想把新的比较函数写成lambda表达式,可以直接写成类的函数,但是需要注意的是要写成类的静态函数,不然会报错…(好像是说compare函数必须要写成static,百度上其他人也遇到鬼类似的错误)
形式参数列表的const
不是必须要写的。