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]]
想象一下排座位,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]
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