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

406. Queue Reconstruction by Height

2018-02-06 19:16 387 查看
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]]


思路:重新按照身高排序,若相等,按位置排序。然后根据pair.second对应着当前点再一次排序时应该的位置。

代码1:class Solution {
public:
static bool cmp (pair<int, int> a , pair<int, int> b){
if(a.first == b.first ) return a.second < b.second ;
return a.first > b.first ;
}

vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int>> ans ;
ans.clear() ;
sort(people.begin() , people.end() , cmp) ;
for(auto i : people)
//此时前面的人一定都比后面的高所以他们的k就是他们应该在的位置
ans.insert( ans.begin() + i.second , i) ;
return ans ;
}
};代码2:
class Solution {
public:
static bool comp(const pair<int, int> &a,const pair<int, int> &b){
if(a.first>b.first){return true;}
else if(a.first==b.first){return a.second<b.second;}
else{return false;}
}
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
sort(people.begin(),people.end(),comp);
for(int i=0;i<people.size();i++){
if(people[i].second!=i){
pair<int, int> temp=people[i];
people.erase(people.begin()+i);
people.insert(people.begin()+temp.second,temp);
}
}
return people;
}
};
代码3:
struct node{
pair<int, int>val;
int count;
node*left, *right;
node(pair<int, int>n)
{
val = n;
count = 0;
left = NULL, right = NULL;
}
};
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
auto cmp = [](pair<int, int>a, pair<int, int>b){return a.first==b.first?a.second<b.second:a.first>b.first;};
sort(people.begin(), people.end(), cmp);
vector<pair<int,int>>ans;
node* root = NULL;
for(auto temp:people)
{
insert(root, temp.second+1, temp);
}
ans = tra(root);
return ans;
}
void insert(node* &root, int n, pair<int, int>val)
{
if(!root)root = new node(val);
else if(n>(root->count+1))insert(root->right, n - root->count-1, val);
else root->count++, insert(root->left, n, val);
}
vector<pair<int, int>> tra(node* root)
{
vector<pair<int, int>>ans;
stack<node*>sta;
while(!sta.empty()||root)
{
if(root)
{
sta.push(root);
root = root->left;
}
else
{
root = sta.top();
sta.pop();
ans.push_back(root->val);
root = root->right;
}
}
return ans;
}
};
用时最短,没看
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: