Problem:
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]]
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
# 思路
# 1. 先按K值从小到大进行排序,如果K值一样的按照身高从小到大排序
# 2. 从这个排序后得到的序列把满足K值要求的往前插入
people_re = []
# 先按K值从小到大进行排序,如果K值一样的按照身高从小到大排序
index = 0
people.sort(cmp=lambda x, y: cmp(x[1], y[1])) # 先按照K值从小到大排序
# 再按照高度从小到大排序
for i in range(1, len(people)):
if people[i][1] != people[i-1][1]:
for person in sorted(people[index:i], key=lambda x: x[0]):
people_re.append(person)
index = i
for person in people[index:]:
people_re.append(person)
# 从这个排序后得到的序列把满足K值要求的往前插入
for i in range(len(people_re)):
height = people_re[i][0] # 获取高度
k = people_re[i][1] # 获取站在他前面的比他高的人数
count = 0 # 位置计数,如果前面的人比他高则+1
insert_index = 0 # 插入的位置
flag = False # 设置一个需要变动位置的标识符
for j in range(i):
if people_re[j][0] >= people_re[i][0] and count < k:
flag = True
count += 1
insert_index = j+1
# 当获得了满足条件的位置的时候,应该要继续遍历
# 因为如果位置计数count已经到达k值,但是如果在要插入的位置之后有人比他矮,我们继续移动到这个人之后
if count == k and people_re[j][0] < people_re[i][0]:
insert_index = j+1
# 满足插入条件,则进行插入
if flag:
tar = people_re.pop(people_re.index(people_re[i])) # 先离队
people_re.insert(insert_index, tar) # 再插入
return people_re

本文介绍了一种用于根据人员的高度及前方比其高的人员数量来重建队列的算法。该算法首先依据特定规则对输入列表进行排序,然后通过迭代检查每个元素以确保其正确地插入到最终队列中。

4467

被折叠的 条评论
为什么被折叠?



