[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)

--

--

--

Interesting in any computer science.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

First principle for the Zettelkasten method.

Rails101:Post 實作edit/destroy

How to move Terra swap LP to Astroport LP

Self-Healing: How to Keep Your Systems Live

Stream and recognise people from a webcam with Go and Facebox

Deploy Atlas Hive Hook — Part 2

Creating a Peer-to-Peer Web App with OrbitDB and StencilJS (Part 2)

How to become better at software estimations (Part 1)

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.

More from Medium

Sorting Algorithms Explained Using Python: Heap Sort

Glass Cube and Dots

[LeetCode]#2114. Maximum Number of Words Found in Sentences

From Python To Java (Part 5) — Dictionaries (Python) VS HashMaps (Java)

LeetCode #1332 | Remove Palindromic Subsequences