【leetcode】【M】406. Queue Reconstruction by Height【95】


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

Subscribe to see which companies asked this question



貪心。

最開始,做法是,按照個子大小排序,從小到大

然後一個一個安排,判斷是不是要放到res裏面

判斷的方法是,判斷整個res裏面有幾個能擋住他的,如果個數跟k相等,那就放進去

整個過程循環進行, 直到p裏面一個元素都沒有了

然後,結果雖然對,超時了。


找人家的算法。


想象一下排座位,h是身高,k是某個小朋友最多允許幾個人擋住他(貌似不是很恰當)。

對於單個小朋友來說,只有比他高才會擋住他,所以我們先按h的標準排最高的一批小朋友,這樣一來後面批次的小朋友不會影響自己,因爲後來比自己矮的不可能擋住自己。
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

[7,0]和[7,1]先排好。
同一批次裏,K小的在前面,這個很好理解。。

第二批小朋友是身高爲6的,[6,1],他要保證只有1個人擋住他,他坐到剛纔2個人之間就行了。
[7,0] [6,1] [7,1]

第三批是身高爲5的,[5,0]和[5,2],[5,0]想近距離觀察美女老師,然而,目前在坐的所有人都比他高(我不是針對誰,還沒坐下的都是勒澀),他就跑去第一排了。至於[5,2],性慾不那麼旺盛,被2個人擋住也無所謂,於是坐到2個人後面。
[5,0] [7,0] [6,1] [7,1]
[5,0] [7,0] [5,2] [6,1] [7,1]
然後是最後一個小朋友[4,4],他可能比較像我,坐懷不亂,正人君子,道德楷模,上課的時候心無旁騖,不需要看美女老師,所以前面4個人無所謂,他跑到4個人後面
[5,0] [7,0] [5,2] [6,1] [4,4] [7,1]

BB半天說白了一句話,h大的前面,h一樣的k小的在前面。
根據這句話設立PQ的判斷規則就行了。。

你看,說的很明白了,顯然這個算法更快也更簡潔


class Solution(object):
    def reconstructQueue(self, people):
        if not people: return []

        # obtain everyone's info
        # key=height, value=k-value, index in original array
        peopledct, height, res = {}, [], []

        for i in xrange(len(people)):
            p = people[i]
            if p[0] in peopledct:
                peopledct[p[0]] += (p[1], i),
            else:
                peopledct[p[0]] = [(p[1], i)]
                height += p[0],

        height.sort()      # here are different heights we have

        # for i in peopledct.items():
        #     print i

        # sort from the tallest group, to ensure that the tallest is always in the front
        for h in height[::-1]:
            peopledct[h].sort()
            for p in peopledct[h]:
                res.insert(p[0], people[p[1]])
                # p[0] mean the number of person higher than him on front of him
            # print res

        return res




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章