• 【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)
  • 相关阅读:
    sort_action
    jedis
    ClassNotFoundException
    mysql-test-run.pl
    mysql 5.6 bug
    The basic principle of test case 修改引擎
    mysql 执行计划走索引
    mysql 执行计划走索引
    14.1.2 Checking InnoDB Availability 检查InnoDB 可用性:
    14.1.2 Checking InnoDB Availability 检查InnoDB 可用性:
  • 原文地址:https://www.cnblogs.com/seyjs/p/11232032.html
Copyright © 2020-2023  润新知