Before, I traverse the vector times and times to find the one to insert into the new vector each time, with a low efficiency. However, I was impressed by another ingenious method and used it without hesitation. We first sort the vector descending first element, then the ascending second element. After that, we just insert each element in the sorted vector based on its second value. An amazing way to solve this problem.
class Solution {
public:
static bool comp(pair<int, int> a, pair<int, int> b){
return a.first > b.first || (a.first == b.first && a.second < b.second);
}
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int>> re;
int size = people.size();
sort(people.begin(),people.end(),comp);
for(int i=0;i<people.size();i++){
re.insert(re.begin()+people[i].second,people[i]);
}
return re;
}
};