Description,
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]]
Bucket sort implemted in Python
Starting with the tallest ones, [7, 0], [7, 1], put them in order of k value.
Then work with the second tallest ones, [6, 1], by inserting them one by one in order of their k values.
Time complexity: O(nlongn)
Runtime: 153ms
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
ret = []
bucket = dict()
for p in people:
height = p[0]
if height not in bucket:
bucket[height] = []
bucket[height].append(p)
else:
bucket[height].append(p)
heightList = bucket.keys()
heightList.sort(reverse=True)
for h in heightList:
hList = bucket.get(h)
hList.sort(key=lambda x : x[1])
for p in hList:
ret.insert(p[1], p)
return ret
Runtime: 153ms