您的位置:首页 > 产品设计 > UI/UE

[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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: