在C ++中按高度进行队列重构
考虑一下,我们有一个随机排队的人名单。如果每个人都用一对整数(h,k)描述,其中h是身高,k是在他前面的身高大于或等于h的人数。我们必须定义一种重建队列的方法。因此,如果给定的数组像[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]],则输出为[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
为了解决这个问题,我们将遵循以下步骤-
根据以下比较策略对给定数组进行排序
如果a[0]=b[0],则返回a[1]>b[1],否则返回a[0]<b[0]
创建一个称为ans的向量
对于我在给定数组的范围大小降至0
将(ans的第一个元素+p[i,1],p[i])插入到ans数组中
返回ans
示例
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
bool cmp(vector <int> a, vector <int> b){
if(a[0] == b[0])return a[1] > b[1];
return a[0] < b[0];
}
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& p) {
sort(p.begin(), p.end(), cmp);
vector < vector <int> > ans;
for(int i = p.size()-1; i>=0; i--){
ans.insert(ans.begin() + p[i][1], p[i]);
}
return ans;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2}};
print_vector(ob.reconstructQueue(v));
}输入值
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
输出结果
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]