用C++按身高重建队列
设我们有一群随机的人站在队列里。如果每个人都由一对整数(h、k)进行描述,其中 h 是身高,k 是他前面身高比他大或者等于他的人数,我们必须定义一种方法来重建队列。因此,如果给定数组为[[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的向量
- 对于i在给定数组大小到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]]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Java
PHP