python--leetcode406. Queue Reconstruction by Height
来源:互联网 发布:阿里云虚拟主机ip地址 编辑:程序博客网 时间:2024/06/05 14:11
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]]
本题的题目意思是给你一个随机排序的list,list中每个元素为(h,k)。h为此人身高,k为身高大于等于此人的人数。请写一个算法重构这个队列。
看上去比较复杂,所以得细细讲一下解题思路:
步骤如下:
1、挑出最高的一群人,并在一个子列表(S)中排序。 既然没有其他人比他们高,所以每个人的下标就和他的k值一样。
2、对于第二个最高的组,将它们中的每一个以k值为下标插入(S)。之后都以此类推。
例如。
输入:[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
步骤1之后的子阵列:[[7,0],[7,1]]
步骤2之后的子阵列:[[7,0],[6,1],[7,1]]
...
看代码:
2、对于第二个最高的组,将它们中的每一个以k值为下标插入(S)。之后都以此类推。
例如。
输入:[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
步骤1之后的子阵列:[[7,0],[7,1]]
步骤2之后的子阵列:[[7,0],[6,1],[7,1]]
...
看代码:
class Solution(object): def reconstructQueue(self, people): if not people: return [] # obtain everyone's info # key=height, value=k-value, index in original array peopledct, height, res = {}, [], [] for i in range(len(people)): p = people[i] if p[0] in peopledct: peopledct[p[0]] += (p[1], i), else: peopledct[p[0]] = [(p[1], i)] height += p[0], height.sort() # here are different heights we have # sort from the tallest group for h in height[::-1]: peopledct[h].sort() for p in peopledct[h]: # 此时p[0]为插入位置,people[p[1]]为要插入的元素 res.insert(p[0], people[p[1]]) return ress=Solution()print(s.reconstructQueue([[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]))
阅读全文
1 0
- python--leetcode406. Queue Reconstruction by Height
- leetcode406. Queue Reconstruction by Height
- LeetCode406. Queue Reconstruction by Height
- LeetCode406. Queue Reconstruction by Height
- Leetcode406 Queue Reconstruction by Height
- leetcode406 Queue Reconstruction By Height java
- 26.leetCode406:Queue Reconstruction by Height
- LeetCode406. Queue Reconstruction by Height Add to List
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- Queue Reconstruction by Height
- 在mysql中使用group by和order by取每个分组中日期最大一行数据
- 快速排序的JAVA实现
- 第一讲 数系发展史纲
- 6.5华式温度与摄氏度的转化
- 创建字体信息设置界面
- python--leetcode406. Queue Reconstruction by Height
- 如何禁用笔记本触摸板
- NOIP2016天天爱跑步
- 流程控制语句详解
- 鸡兔同笼问题
- 滚动条的应用
- Mnemonic Descent Method:A recurrent process applied for end-to-end face alignment
- 任意输入一个三位数将他的百位变为各位依次反序,
- 【c++】类&对象详解