使用哈希图进行相对排序


#include <bits/stdc++.h>
using namespace std;
int main()
{
int T,i;
map<int,int> h;
cin>>T;
while(T--)
{
int n,m;
cin>>n>>m;
int arr1[n];
int arr2[m];
for(i=0;i<n;i++)
{
cin>>arr1[n];
}
for(i=0;i<m;i++)
{
cin>>arr2[m];
}
for(i=0;i<n;i++)
{
h[arr1[i]]++;
}
map<int,int>:: iterator itr;
for(int i=0;i<m;i++)
{    //itr=h.find(arr2[i]);
if(h.find(arr2[i])!=h.end())
{
itr=h.find(arr2[i]);
}
while(itr->second--)
{
cout<<itr->first<<" ";
}
}

for(auto x: h)
{
if(x.second!=0)
{
while(x.second--)
{
cout<<x.first<<" ";
}
}
}


cout<<endl;
}
}

给定两个大小分别为 N 和 M 的数组 A1[] 和 A2[]。任务是使元素之间的相对顺序与 A2 中的相对顺序相同的方式对 A1 进行排序。对于 A2 中不存在的元素,最后按排序顺序附加它们。还假设 A2[] 中的元素数小于或等于 A1[] 中的元素数,并且 A2[] 具有所有不同的元素。注意:预期时间复杂度为 O(N log(N((。输入 A1[]=2 1 2 5 7 1 9 3 6 8 8 A2[]=2 1 8 3 输出: 2 2 1 1 8 8 3 5 6 7 9

我正在尝试制作 A1[] 中元素频率的哈希图。 之后,我尝试将哈希图的键与 A2[] 的元素相匹配。 我遇到了分段错误。我做错了什么。

vector<int> relSort(vector<int> A1, vector<int> A2) {
vector<int> res;
for (int i=0; i<A2.size(); i++){
for (int j=0; j<A1.size(); j++){
if (A1[j] == A2[i]){
res.push_back(A2[i]);
A1.erase(A1.begin()+j);
j--;
}
}
}
sort(A1.begin(), A1.end());
for (int i=0; i<A1.size(); i++){
res.push_back(A1[i]);
}
return res;
}

最新更新