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" />
相关文章推荐
- 406. Queue Reconstruction by Height(根据身高重排队列)
- LeetCode 根据前序和中序遍历构造二叉树的三种解法
- 根据前序中序,中序后序遍历构造二叉树 leetcode105 106
- [leetcode] 根据String数组构造TreeNode,用于LeetCode树结构相关的测试用例
- [LeetCode] Queue Reconstruction by Height 根据高度重建队列
- LeetCode(Construct Binary Tree from Inorder and Postorder Traversal)根据二叉树的中序和后续构造二叉树
- 有一个单向循环链表队列,从头开始报数,当报到m或者m的倍数的元素出列,根据出列的先后顺序重新组成单向循环链表。
- [LeetCode] Queue Reconstruction by Height 身高队列
- leetcode_406. Queue Reconstruction by Height 按身高h和比他高的人的个数k的二元组(h,k) 排队
- LeetCode之根据升序的单链表构造平衡二叉树
- 数据结构Step by Step之树(1)- 二叉树 前序、中序、后序 LeetCode105根据前序中序的顺序构造树
- 第3章 栈和队列综合习题(leetcode+vjudge)
- leetcode Binary Tree Zigzag Level Order Traversal 层序遍历 双队列
- HDOJ 4671 Backup Plan 构造优先队列
- 例题:输入学生的各项资料,然后根据学生的分数,重新排序。重新复习结构体,集合,数组,for循环,冒泡排序,水平符的使用。
- List<Map>集合根据Map里某个key对List集合重新排序介绍
- LeetCode | Reorder List(链表重新排序)
- 【Android开发】Bundle和Intent实例1-实现根据身高计算标准体重
- Leetcode 108 Convert Sorted Array to Binary Search Tree 有序数组构造平衡二叉查找树
- 自己编写的两级队列的线程池(根据ThreadPoolExecuuor)