[LeetCode]#1122. Relative Sort Array

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]
class Solution:
def relativeSortArray(self, arr1, arr2):
d1 = {}
for i in arr2:
d1[i] = 1
not_match = []
d2 = {}
for i in arr1:
if i in d1:
d2[i] = d2.setdefault(i,0) + 1
else:
not_match.append(i)
match = []
for i in arr2:
match += [i] * d2[i]
return match + sorted(not_match)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store