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.

  • arr1.length, arr2.length <= 1000
  • 0 <= arr1[i], arr2[i] <= 1000
  • Each arr2[i] is distinct.
  • Each arr2[i] is in arr1.

开一个count数组统计arr1中出现元素的个数,然后按照arr2里的顺序填充答案,最后别忘记count里可能有剩余的元素不在arr2里,也要补上

class Solution(object):
    def relativeSortArray(self, arr1, arr2):
        """
        :type arr1: List[int]
        :type arr2: List[int]
        :rtype: List[int]
        """
        ans = []
        count= [0] * 1001
        for value in arr1:
            count[value] += 1
        for value in arr2:
            while count[value] > 0:
                ans.append(value)
                count[value] -= 1
        for value in range(1001):
            while count[value] > 0:
                ans.append(value)
                count[value] -= 1
        return ans
原文地址:https://www.cnblogs.com/whatyouthink/p/13208477.html