Leetcode 1122. Relative Sort Array
Given two arrays arr1
and arr2
, the elements of arr2
are distinct, and all elements in arr2
are also in arr1
. Sort the elements of arr1
so that the relative ordering of items in arr1
are the same as in arr2
. Elements that do not appear in arr2
should be placed at the end of arr1
in ascending order.
Example 1:
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]
Example 2:
Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]
Output: [22,28,8,6,17,44]
arr2
are in arr1
?
arr1
that are not in arr2
?
arr1
?
arr1
should be handled accordingly.arr1
.arr2
: Use arr2
to determine the initial order of elements, respecting their counts.arr1
that are not in arr2
.#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
std::vector<int> relativeSortArray(std::vector<int>& arr1, std::vector<int>& arr2) {
std::unordered_map<int, int> countMap;
for (int num : arr1) {
countMap[num]++;
}
std::vector<int> result;
// Adding elements from arr2 in the required order
for (int num : arr2) {
while (countMap[num] > 0) {
result.push_back(num);
countMap[num]--;
}
}
// Adding remaining elements from arr1 not in arr2
std::vector<int> remainingElements;
for (const auto& entry : countMap) {
while (entry.second > 0) {
remainingElements.push_back(entry.first);
entry.second--;
}
}
std::sort(remainingElements.begin(), remainingElements.end());
// Merge results
result.insert(result.end(), remainingElements.begin(), remainingElements.end());
return result;
}
int main() {
std::vector<int> arr1 = {2,3,1,3,2,4,6,7,9,2,19};
std::vector<int> arr2 = {2,1,4,3,9,6};
std::vector<int> result = relativeSortArray(arr1, arr2);
for(int num : result) {
std::cout << num << " ";
}
return 0;
}
arr1
.arr2
.arr1
.This approach ensures that the algorithm runs efficiently and meets the problem requirements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?