【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