一.问题描述
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]
Constraints:
arr1.length, arr2.length <= 10000 <= arr1[i], arr2[i] <= 1000- Each
arr2[i]is distinct. - Each
arr2[i]is inarr1.
二.解题思路
这道题主要就是计算每个数有多少个,然后根据arr2的顺序生成一个数组。
主要的考察点应该是map的使用,或者说python的字典。
具体解法:
1.计算arr1中每个元素出现的次数,保存在一个字典中
2.遍历arr2,遍历一个数就通过我们保存的字典查找该数在arr1中出现的次数,然后加到结果数组的末尾,并从该字典中把该元素删掉。
3.字典中剩下的是不存在arr2中的元素,把这些元素保存在一个列表中,排序后加到结果数组后面。
需要注意的地方就是,extend()函数只操作元素组,没有返回值。
时间复杂度分析:
假设arr1中出现在arr2中的元素有m个,未出现的有n个
时间复杂度:如果未出现在arr2中的元素很多的话,那排序消耗时间多,为O(nlogn),否则的花为O(m+n).
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac。
三.源码
from collections import Counter
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
no_app,rst=[],[]
num2cnt=Counter(arr1)
for num in arr2:
rst.extend(num2cnt[num]*[num])
del num2cnt[num]
for key in num2cnt:
no_app.extend(num2cnt[key]*[key])
rst.extend(sorted(no_app))
return rst
本文详细解析了LeetCode上的一道经典题目——相对排序数组。通过使用Python的Counter和字典,文章提供了一种高效解决问题的方法。首先,计算arr1中每个元素的出现次数,然后根据arr2的顺序生成结果数组,最后对未出现在arr2中的元素进行排序并添加到结果数组的末尾。
401

被折叠的 条评论
为什么被折叠?



