[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

All About that Sass

How Software Development tracking is broken

Scheduling Jobs with cron.yaml in Golang App

The perfect dorm room assignment: Exploring the bipartite matching problem with Neo4j

Bipartite graph showing rooms and students

Installing the Flutter in Windows.

THE UNIQUENESS OF CRODO

Rapid Application Development: Evolving How Developers Work

What is the best development framework?

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

How to implement a Queue class using deque. PYTHON data structures and algorithm.

[LeetCode]#1967. Number of Strings That Appear as Substrings in Word

LeetCode Patterns Adventure 7 — Maximum Subarray

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