刷题406. Queue Reconstruction by Height
Posted siweihz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了刷题406. Queue Reconstruction by Height相关的知识,希望对你有一定的参考价值。
一、题目说明
题目406. Queue Reconstruction by Height,队列每个元素包括(h,k)
,其中h是身高,k是身高不低于h的数量,请按照k和h重构队列。难度是Medium!
二、我的解答
这个题目理论上不难,但是细节不好处理。代码如下:
class Solution{
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people){
vector<vector<int>> res;
map<int,vector<int> > mapFronts;
for(int i=0;i<people.size();i++){
mapFronts[people[i][1]].push_back(people[i][0]);
}
for(map<int,vector<int>>::iterator iter=mapFronts.begin();iter!=mapFronts.end();iter++){
//cout<<iter->first<<":";
vector<int> cur = iter->second;
sort(cur.begin(),cur.end());
vector<int> tmp;
for(int i=0;i<cur.size();i++){
//cout<<cur[i]<<" ";
tmp.clear();
tmp.push_back(cur[i]);
tmp.push_back(iter->first);
if(iter->first == 0){
res.push_back(tmp);
}else{
int curH = cur[i];
int t = 0,num=0;
int bigNum = iter->first;
while(t<res.size() && num<bigNum){
if(res[t][0] >= curH){
num++;
}
t++;
}
if(t<res.size()){
while(t<res.size() && res[t][0] < curH){
t++;
}
}
if(t==res.size()){
res.push_back(tmp);
}else{
vector<vector<int>>::iterator itTemp;
itTemp = res.begin();
itTemp = itTemp + t;
res.insert(itTemp,tmp);
}
}
}
}
return res;
}
};
性能如下:
Runtime: 80 ms, faster than 72.71% of C++ online submissions for Queue Reconstruction by Height.
Memory Usage: 14.5 MB, less than 9.52% of C++ online submissions for Queue Reconstruction by Height.
三、优化措施
这个用到map,用到sort排序。
以上是关于刷题406. Queue Reconstruction by Height的主要内容,如果未能解决你的问题,请参考以下文章
406. Queue Reconstruction by Height
[leetcode-406-Queue Reconstruction by Height]
LeetCode 406: Queue Reconstruction
[leetcode] 406.Queue Reconstruction by Height