1 import collections 2 class Solution: 3 def relativeSortArray(self, arr1: 'List[int]', arr2: 'List[int]') -> 'List[int]': 4 n1 = len(arr1) 5 n2 = len(arr2) 6 if n2 == 0: 7 return arr1 8 distinct = collections.OrderedDict() 9 others = [] 10 for i in range(n2): 11 distinct[arr2[i]] = 0 12 #print(distinct) 13 for j in range(n1): 14 if arr1[j] in distinct: 15 distinct[arr1[j]] += 1 16 else: 17 others.append(arr1[j]) 18 res = [] 19 for k,v in distinct.items(): 20 res = res + [k] * v 21 others = sorted(others) 22 res = res + others 23 return res
先记录arr2中元素,在arr1中出现的次数,保存为有序字典。另保存不在arr2中的元素。
先拼接字典中的元素,再对另外部分排序,追加到结果数组的末尾。