leetcode 406 Queue Reconstruction by Height
z

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

1
2
3
4
5
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]]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
res = []
people_dic = {}
heights = []

for i, (height, k) in enumerate(people):
if height not in people_dic:
heights.append(height)
people_dic[height] = [(k, i)]
else:z
people_dic[height].append((k, i))

heights.sort()

for h in heights[::-1]:
t = people_dic[h]
t.sort()

for (k,i) in t:
res.insert(t[0], people[t[1]])

return res

KeyNotes:

  • 总的来说,先需要将每一个people按照height进行从大到小的排序,每一次先对height高的人分配位置。

  • 当有两个人的height一样高时,那就会根据k来进行从小到大的排序。

  • 比如说,[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]],那最先开始,我们需要对[7,0],[7,1]来排序,

    • 此时, ans = [[7, 0], [7, 1]]

    • 接下来对[5, 0], [5, 2]进行排序:

      • 对[5, 0], 需要插入在ans的第0个位置, 得到ans = [[5,0] ,[7, 0], [7, 1]]
      • 对[5, 2], 需要插入到ans的第2个位置, 得到ans = [[5, 0], [7, 0], [5, 2], [7, 1]]

      and so on …