跳至主要内容

1122. Relative Sort Array

  • 使用 TreeMap
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2)
{
map<int, int> countMap;
for (int num : arr1) ++countMap[num];

vector<int> res;
for (int num : arr2)
{
for (int i = 0; i < countMap[num]; ++i)
{
res.push_back(num);
}
countMap.erase(num);
}

for (auto a : countMap)
{
for (int i = 0; i < a.second; ++i)
{
res.push_back(a.first);
}
}
return res;
}
};
  • T: O(n+m+k)O(n + m + k)
  • S: O(k)O(k)