class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
res = []
for num2 in arr2:
for i, num1 in enumerate(arr1):
if num1 == num2:
res.append(num1)
arr1[i] = -1
arr1.sort()
for i in range(len(res), len(arr1)):
res.append(arr1[i])
return resWhere is the size of the array , and is the size of the array .
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
arr2_set = set(arr2)
arr1_count = defaultdict(int)
end = []
for num in arr1:
if num not in arr2_set:
end.append(num)
arr1_count[num] += 1
end.sort()
res = []
for num in arr2:
for _ in range(arr1_count[num]):
res.append(num)
return res + endWhere is the size of the array , and is the size of the array .
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
count = {}
for num in arr1:
count[num] = count.get(num, 0) + 1
res = []
for num in arr2:
res += [num] * count.pop(num)
for num in sorted(count):
res += [num] * count[num]
return resWhere is the size of the array , and is the size of the array .
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
max_val = max(arr1)
count = [0] * (max_val + 1)
for num in arr1:
count[num] += 1
res = []
for num in arr2:
res += [num] * count[num]
count[num] = 0
for num in range(len(count)):
res += [num] * count[num]
return resWhere is the size of the array , is the size of the array , and is the maximum value in the array .
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
index = {num: i for i, num in enumerate(arr2)}
return sorted(arr1, key=lambda x: (index.get(x, 1000 + x)))Where is the size of the array , and is the size of the array .