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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,847評論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,082評論 0 23
  • 1. 嘿!好久不見! 我想,今天的你還是老樣子,剛剛忙完手頭上的工作,刷著手機給自己稍微放空的時間。謝謝你,恰好想...
    我是夾心_閱讀 432評論 0 0
  • 普拉提的好處不僅僅局限于幫你收腹減腰圍,它還可以幫你鍛煉全身,讓你的身體線條更完美。 普拉提訓(xùn)練法是由德國人約瑟夫...
    愛蹦跶閱讀 511評論 0 9
  • 上課為秘密和偷情的酵母提供了溫床,但是也公開炫耀提供了溫床。
    CNBLUEone閱讀 69評論 0 0

友情鏈接更多精彩內(nèi)容