Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don’t appear in arr2 should be placed at the end of arr1 in ascending order.
Example 1:
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]
import functools
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
#先给arr2进行赋权值
weight = [0]*(1000+1)
count = 0
for i in arr2:
weight[i] = count
count+=1
extra = []
extracount = 0
for j in arr1:
if j not in arr2:
extracount+=1
weight[j] = 10000
extra.append(j)
def custom_sorted(x,y):
if weight[x] > weight[y]:
return 1
if weight[x] <= weight[y]:
return -1
return sorted(arr1,key=functools.cmp_to_key(custom_sorted))[0:(len(arr1)-extracount)] + sorted(extra)
注意:在python3中:
- sorted() 函数可以返回一个新的列表
- 在python3中如果要自定义排序函数的话,需要引入functools模块的cmp_to_key。然后通过向sorted() 中传入关键字参数。