406. Queue Reconstruction by Height

问题描述

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.

思路

First, sort the list people, so that people with lower k stand in front of those with higher k. Also, people with greater h will stand in front of people with smaller h.
对于 h相同的人, k 小的人,会站在 k大的人的后面。 并且排序过后h的人站在前面
Then, create an empty list.
在排序过后,每个k值表示这个人要站的位置。
因为h值在减小,在某个人前面插入别的人,并不会影响到k值。

    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        sortByK = sorted(people, key=lambda s: s[1])
        sortByH = sorted(sortByK, key=lambda s: s[0], reverse=True)
        ans = []
        for i in sortByH:
            ans.insert(i[1], i)
        return ans
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,812评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,972评论 0 23
  • 1. 嘿!好久不见! 我想,今天的你还是老样子,刚刚忙完手头上的工作,刷着手机给自己稍微放空的时间。谢谢你,恰好想...
    我是夹心_阅读 429评论 0 0
  • 普拉提的好处不仅仅局限于帮你收腹减腰围,它还可以帮你锻炼全身,让你的身体线条更完美。 普拉提训练法是由德国人约瑟夫...
    爱蹦跶阅读 510评论 0 9
  • 上课为秘密和偷情的酵母提供了温床,但是也公开炫耀提供了温床。
    CNBLUEone阅读 69评论 0 0

友情链接更多精彩内容