【leetcode】1122. Relative Sort Array
题目如下:
Given two arrays
arr1andarr2, the elements ofarr2are distinct, and all elements inarr2are also inarr1.Sort the elements of
arr1such that the relative ordering of items inarr1are the same as inarr2. Elements that don't appear inarr2should be placed at the end ofarr1in 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.
解题思路:题目很简单,求出arr1和arr2的交集以及交集中每个元素出现的次数,按元素在arr2中的顺序排列好,最后再加上arr1中不在arr2里面的元素即可。
代码如下:
class Solution(object): def relativeSortArray(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: List[int] """ dic = {} for i in arr2: dic[i] = 1 not_in_2 = [] dic1 = {} for i in arr1: if i in dic: dic1[i] = dic1.setdefault(i,0) + 1 else: not_in_2.append(i) res = [] for i in arr2: res += [i] * dic1[i] return res + sorted(not_in_2)
浙公网安备 33010602011771号