Skip to content

Commit 8da8cb4

Browse files
authored
Update 406._Queue_Reconstruction_by_Height.md
1 parent 1c6f302 commit 8da8cb4

File tree

1 file changed

+34
-10
lines changed

1 file changed

+34
-10
lines changed
Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,37 @@
1-
### 406. Queue Reconstruction by Height
1+
# 406. Queue Reconstruction by Height
22

3-
题目:
4-
<https://leetcode.com/problems/queue-reconstruction-by-height/>
3+
**<font color=red>难度: Medium</font>**
54

5+
## 刷题内容
66

7-
难度:
7+
> 原题连接
88
9-
Medium
9+
* https://leetcode.com/problems/queue-reconstruction-by-height/description/
1010

11+
> 内容描述
12+
13+
```
14+
15+
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.
16+
17+
Note:
18+
The number of people is less than 1,100.
19+
20+
21+
Example
22+
23+
Input:
24+
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
25+
26+
Output:
27+
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
28+
```
29+
30+
## 解题方案
31+
32+
> 思路 1
33+
******- 时间复杂度: O(NlgN)******- 空间复杂度: O(1)******
1134

12-
思路:
1335
People are only counting (in their k-value) taller or equal-height others standing in front of them.
1436
So a smallest person is completely irrelevant for all taller ones. And of all smallest people,
1537
the one standing most in the back is even completely irrelevant for everybody else. Nobody is counting that person.
@@ -26,18 +48,20 @@ Sorting the people from the first-tallest to the last-smallest, and inserting th
2648

2749
参考[stefan](https://leetcode.com/problems/queue-reconstruction-by-height/discuss/89359)
2850

51+
不算返回结果res的话,空间复杂度为O(1)
52+
2953
```python
3054
class Solution(object):
3155
def reconstructQueue(self, people):
3256
"""
3357
:type people: List[List[int]]
3458
:rtype: List[List[int]]
3559
"""
36-
people.sort(key=lambda (h, k): (-h, k))
37-
queue = []
60+
people.sort(key = lambda x: (-x[0], x[1]))
61+
res = []
3862
for p in people:
39-
queue.insert(p[1], p)
40-
return queue
63+
res.insert(p[1], p)
64+
return res
4165
```
4266

4367

0 commit comments

Comments
 (0)