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

Leetcode解题报告:406. Queue Reconstruction by Height

2016-11-14 19:45 501 查看
题意:

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.

难度:medium

解题思路:

这道题的意思是给出每个人的身高h和排在这个人之前的所有人中身高不小于他的人数k。 每次k为0的所有人中,身高最低的那个首先加入答案数组,这样可以保证他的位置不会错。 那么每次加入一个人到答案数组以后,对剩余所有人中身高不比他高的人k-1,再把k=0的人中身高最低的加进答案数组,重复操作直到所有人都排进答案数组。 

时间复杂度为O(n^2)

class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int> > ans(people.size());
vector<pair<int, int> > temp(people.size());
for(int i = 0;i<people.size();i++)
{
temp[i]=people[i];
}
for(int i = 0;i<temp.size();i++)
{

int curmin=-1;
int curin=0;
for(int j = 0;j<temp.size();j++)
{
if(temp[j].second==0)
{
if((temp[j].first&
4000
lt;curmin||curmin==-1)&&temp[j].first>=0)
{
curmin=temp[j].first;
curin=j;

}
}
}
ans[i].first=people[curin].first;
ans[i].second=people[curin].second;
temp[curin].first=-1;
for(int j = 0;j<temp.size();j++)
{
if(temp[j].first<=ans[i].first&&temp[j].first!=-1)
{
temp[j].second--;
}
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: