406. Queue Reconstruction by Height
https://leetcode.com/problems/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.
Note: The number of people is less than 1,100.
Example
Thoughts
给由整数对(h, k)组成的数组,ki表示在原数组中h>=hi并排在前面的元素个数,让还原原数组。因为k是排在前面且大于h的数,按照h从大到小排序,并且同一h的k小的排前面。新建列表,按照顺序把pair(h, k)插入k位置,也就满足了它前面有k个>=h元素;后面的元素即使插在它前面,根据排序顺序也不会比h大,不会影响k的正确。
Code
Analysis
时间复杂度O(NlgN).
Last updated
Was this helpful?