目录
一、题目
二、分析+代码
一、题目
二、分析+代码
核心计数排序!!!
class Solution {
public:
vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {
int n = arr1.size();
int arr1_Max = INT_MIN;
for (int i = 0; i < n; i++)
{
arr1_Max = arr1_Max >= arr1[i] ? arr1_Max : arr1[i];
}
vector<int>data(arr1_Max+1, 0);
vector<int>ret(arr1_Max + 1, 0);
int i = 0;
while (i < n)
{
data[arr1[i]]++;
i++;
}
int k = 0;
for (int i = 0; i < arr2.size(); i++)
{
if (data[arr2[i]] != 0)
{
while (data[arr2[i]] > 0)
{
ret[k++] = arr2[i];
data[arr2[i]]--;
}
}
}
for (int i = 0; i < data.size(); i++)
{
while (data[i] > 0)
{
ret[k++] = i;
--data[i];
}
}
vector<int>result;//将超出arr2数组长度后面全部为0 的数据去掉
for(int k=0;k<arr1.size();k++)
{
result.push_back(ret[k]);
}
return result;
}
};