zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    第四周助教小结 北软
    第二周工作小结 北软
    第六周助教小结 北软
    第七周周小结 北软
    第八周周小结 北软
    几句话了解元数据(Metadata)
    App测试点(二)
    Pytest单元测试
    UnitTest单元测试
    【模板】单源最短路径
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13208477.html
Copyright © 2011-2022 走看看