这道题目不是很难,但是思路也很好玩.
通过这道题,我们还可以顺便掌握c++11中刚刚引入的lambda表达式,非常棒!
题目描述
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.
sample
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 | 如果第一个元素不等,那么大的在前。 |
所以变化如下。
- 初始状态:[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
- 排序之后:[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
接下来从第二个元素开始插入,按照如下规则进行排序。
1 | 将两个数构成的数组插入到数组中第二个数的位置。 |
插入之后的变化依次如下,这里可以从第二个元素开始进行判断
- 插入[7,1]元素:[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
- 插入[6,1]元素:[[7,0], [6,1], [7,1], [5,0], [5,2], [4,4]]
- 插入[5,0]元素:[[5,0], [7,0], [6,1], [7,1], [5,2], [4,4]]
- 插入[5,2]元素:[[5,0], [7,0], [5,2], [6,1], [7,1], [4,4]]
- 插入[4,4]元素:[[5,0], [7,0], [5,2], [6,1], [4,4],[7,1]]
巧妙之处
- 要学会使用lambda表达式,也就是如下的代码。
1 | sort(people.begin(), people.end(),[](vector<int>& a,vector<int>& b){ |
如果不使用lambda表达式那么就需要写成如下模样。
1 | static bool cmp(vector<int>& a, vector<int> b){ |
- 发现排序之后整个vector可以插入的位置刚刚好是vector中第二个元素的位置。
解题代码
原始代码
1 | class Solution { |
升级代码
上面的那种方法速度比较满,原因在于是在原数组上进行插入同时还要进行删除操作,而如果我们直接新建一个vector来保存结果,那么就只需要插入就可以了,然后速度会有很大的提升。
1 | class Solution { |
再次升级代码
为了代码好看,可以再次升级代码,使用增强的for循环。
1 | class Solution { |
以上,本题结束。