您的位置:首页 > 其它

Leetcode406. 根据身高重新构造队列

2017-10-08 07:55 1531 查看

Leetcode406. Queue Reconstruction by Height

题目

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]]

解题分析

一拿到这道题,可能刚开始会是毫无头绪的,不知从何下手。但粗略想一下,可能会觉得应该将他们按身高排序。

但问题的关键在于要如何根据他们的身高来确定位置,从而实现要求的队列。一种想法是,将他们按身高从小到大排序,然后按照比他们高的人数对应插入位置,如果位置不为空,就遍历数组找到不为空的位置然后插入。之后再遍历数组的每个元素,如果他所在位置在他前面比他高的人数不等于他实际的位置,那么就往后遍历数组,找到第一个比他高的进行位置的交换。这样做不是不可以,但是可能显得有些过于麻烦了。

那有什么更好的做法呢?这里我们用到了vector的insert函数,它表示在对应位置插入元素,如果该位置有元素,就自动将已插入的元素往后移。说实话,这个函数并不怎么用,以至于我都忘记了。结合题目的要求,我们可以往vector里面对应位置插入身高比较高的元素,然后后面如果有位置重叠,就自动将身高比较高的元素往后挪,这样问题就顺利解决了,比上面一种做法也简单了许多。

源代码

class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
int i, size = people.size();
vector<pair<int, int>> v;
sort(people.begin(), people.end(), [](const pair<int, int>& x, const pair<int, int>& y) -> int {
return (x.first > y.first) || (x.first == y.first && x.second < y.second);
});
for (i = 0; i < size; i++) {
v.insert(v.begin() + people[i].second, people[i]);
}
return v;
}
};


以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~

<
4000
link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/production/markdown_views-ea0013b516.css" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐