【leetcode】1122. Relative Sort Array


题目如下:

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 <= 1000
  • 0 <= arr1[i], arr2[i] <= 1000
  • Each arr2[i] is distinct.
  • Each arr2[i] is in arr1.

解题思路:题目很简单,求出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)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM