[leetcode]406. Queue Reconstruction by Height
2017-11-07 12:19
429 查看
greedy
题目:
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]]
思路
首先根据身高从高到低进行排序,如果身高相同,则根据k值从小到大进行排序。由于身高降序排序,则k值就是这个pair插入结果时所在的位置:res.insert(res.begin()+people[i].second, people[i])排序后:
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
1)将[7,0]插入结果
由于k = 0, 则插入结果中的第一个位置:[7,0]
2)将[7,1]插入结果
由于k = 1, 则插入结果中的第二个位置:[7,0],[7,1]
3)将[6,1]插入结果
由于k = 1, 则插入结果中的第二个位置:[7,0],[6,1],[7,1]
4)将[5,0]插入结果
由于k = 0, 则插入结果中的第二个位置:[5, 0], [7,0],[6,1],[7,1]
代码:
class Solution { public: vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { sort(people.begin(), people.end(), cmp); vector<pair<int, int>> res; for (int i = 0; i < people.size(); i++) { res.insert(res.begin()+people[i].second, people[i]); } return res; } private: static int cmp(pair<int, int> a, pair<int, int> b) { if (a.first > b.first || (a.first == b.first && a.second <= b.second)) return true; else return< 8c01 /span> false; } };
相关文章推荐
- leetcode 406. Queue Reconstruction by Height
- Leetcode-406. Queue Reconstruction by Height
- 【LeetCode】 406. Queue Reconstruction by Height
- 【leetcode】406. Queue Reconstruction by Height
- [LeetCode]406. Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height
- 【leetcode】【M】406. Queue Reconstruction by Height【95】
- Leetcode 406. Queue Reconstruction by Height 排队重构 解题报告
- Leetcode 406. Queue Reconstruction by Height
- [LeetCode]406.Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height
- 【LeetCode】406. Queue Reconstruction by Height
- leetcode 406. Queue Reconstruction by Height
- LeetCode--406. Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height
- LeetCode406. Queue Reconstruction by Height
- [leetcode] 406. Queue Reconstruction by Height
- LeetCode406. Queue Reconstruction by Height
- LeetCode 406. Queue Reconstruction by Height