[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]
  1. Use dict function for arr2 to record element. (d1)
  2. Use dict function for arr1 to check whether match arr2 or not. Record the number. (d2)
  3. Check mismatch element.
  4. Sort d2 based on d1 order and add mismatch.
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
Fatboy Slim

Fatboy Slim

Interesting in any computer science.