刷题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排序。

posted @ 2020-04-23 11:31  siwei718  阅读(90)  评论(0编辑  收藏  举报