zoukankan      html  css  js  c++  java
  • 【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)
  • 相关阅读:
    小程序开发学习
    guava 学习一 函数,集合操作
    《构建之法》第四章 两人合作 读后感
    模拟退火学习笔记
    Haywire
    [JSOI2004]平衡点
    CF1039D You Are Given a Tree
    CF797E Array Queries
    [SHOI2014]三叉神经树
    [国家集训队]Tree II
  • 原文地址:https://www.cnblogs.com/seyjs/p/11232032.html
Copyright © 2011-2022 走看看