博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
406. Queue Reconstruction by Height(python+cpp)
阅读量:3700 次
发布时间:2019-05-21

本文共 1737 字,大约阅读时间需要 5 分钟。

题目:

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]]

解释:

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
> reconstructQueue(vector
>& people) {
/* auto comp = [](const pair
& p1, const pair
& p2) { return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second); }; */ sort(people.begin(), people.end(), comp); vector
> res; for (auto& p : people) res.insert(res.begin() + p.second, p); return res; } static bool comp(const pair
& p1, const pair
& p2) { return (p1.first>p2.first) ||(p1.first==p2.first && p1.second

总结:

c++实现二维数组的排序比较麻烦,其实也是需要自己写比较函数,但是比python要麻烦一点。
c++中用[]开头的是lambda表达式。如果不想把新的比较函数写成lambda表达式,可以直接写成类的函数,但是需要注意的是要写成类的静态函数,不然会报错…(好像是说compare函数必须要写成static,百度上其他人也遇到鬼类似的错误)
形式参数列表的const 不是必须要写的。

转载地址:http://xglcn.baihongyu.com/

你可能感兴趣的文章
数据结构---字符串
查看>>
ACM---日记
查看>>
ACM日记
查看>>
ACM日记
查看>>
ACM日记
查看>>
ACM日记
查看>>
4月17日小结
查看>>
4月20日小结
查看>>
4月24日小结
查看>>
4月28日小结
查看>>
5月4日小结
查看>>
第十届山东省省赛总结
查看>>
5月19日小结
查看>>
5月22日小结
查看>>
暑期训练D1
查看>>
暑期训练D2
查看>>
暑期训练D3
查看>>
暑期训练D4
查看>>
暑期训练D5
查看>>
暑期训练D6
查看>>