思路:计数排序,然后根据计数的数组序列重构数组,针对多余的数组元素采取sort函数进行升序排列加在末尾即可。
#include <iostream>
#include <vector>
#include <algorithm>using namespace std;class Solution {
public:vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {vector<int> counter = vector<int>(arr2.size(), 0);vector<int> none;vector<int> result;for (int i = 0; i < arr1.size(); i++){for (int j = 0; j < arr2.size(); j++){if (arr1[i] == arr2[j]) {counter[j]++;break;}else if (j == arr2.size() - 1)none.push_back(arr1[i]);}}int sum;for (auto t : arr2){sum += t;t = sum - t;}for (int q = 0; q < counter.size(); q++) {while (counter[q]--) {result.push_back(arr2[q]);}}sort(none.begin(), none.end());result.insert(result.end(), none.begin(), none.end());return result;}
};int main() {Solution s;vector<int> arr1 = {2,3,1,3,2,4,6,7,9,2,19};vector<int> arr2 = {2,1,4,3,9,6};// s.relativeSortArray(arr1, arr2);for (auto t : s.relativeSortArray(arr1, arr2))cout << t << " ";return 0;
}