Leetcode 1122. Relative Sorting of Arrays

Leetcode 1122. Relative Sorting of Arrays

topic

给你两个数组,arr1 和 arr2,

arr2 中的元素各不相同
arr2 中的每个元素都出现在 arr1 中
对 arr1 中的元素进行排序,使 arr1 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1 的末尾。

Example:

输入:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
输出:[2,2,2,1,4,3,3,9,6,7,19]

Ideas

  • This problem is very convenient to solve with python, and index needs to be used. Here is a chestnut:
arr1 = [1, 2, 3], arr2 = [3, 2, 1]
如果arr1.sort(key=arr2.index)
最后arr1 = [3, 2, 1]
  • For the index method, we can understand it as sorting according to the size of the subscript index. In the above example, in arr2, the index of 3 is 0, the index of 2 is 1, and the index of 1 is 2, because 0 <1 <2, So these three are finally sorted into 3 2 1
  • To understand simply, an array can be sorted according to the relative order of another array

Code-python

class Solution:
    def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
        arr_margin = list(set(arr1) - set(arr2))
        arr_margin.sort()
        return sorted(arr1, key=(arr2 + arr_margin).index)

Guess you like

Origin blog.csdn.net/weixin_43891775/article/details/113173307