[LeetCode] Relative Sort Array

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 such 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<int> relativeSortArray(vector<int>& A, vector<int>& B) {
unordered_map<int,int> ord;
for(int i = 0; i < B.size(); i++) ord[B[i]] = i;
sort(begin(A), end(A), [&](int i, int j) {
if(ord.count(i) and ord.count(j)) return ord[i] < ord[j];
if(!ord.count(i) and !ord.count(j)) return i < j;
return (bool)(ord.count(i));
});
return A;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/06/11/PS/LeetCode/relative-sort-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.