leetcode 1122. Relative Sort Array 解法 python

本文详细解析了LeetCode上的一道经典题目——相对排序数组。通过使用Python的Counter和字典,文章提供了一种高效解决问题的方法。首先,计算arr1中每个元素的出现次数,然后根据arr2的顺序生成结果数组,最后对未出现在arr2中的元素进行排序并添加到结果数组的末尾。

一.问题描述

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.

二.解题思路

这道题主要就是计算每个数有多少个,然后根据arr2的顺序生成一个数组。

主要的考察点应该是map的使用,或者说python的字典。

具体解法:

1.计算arr1中每个元素出现的次数,保存在一个字典中

2.遍历arr2,遍历一个数就通过我们保存的字典查找该数在arr1中出现的次数,然后加到结果数组的末尾,并从该字典中把该元素删掉。

3.字典中剩下的是不存在arr2中的元素,把这些元素保存在一个列表中,排序后加到结果数组后面。

需要注意的地方就是,extend()函数只操作元素组,没有返回值。

时间复杂度分析:

假设arr1中出现在arr2中的元素有m个,未出现的有n个

时间复杂度:如果未出现在arr2中的元素很多的话,那排序消耗时间多,为O(nlogn),否则的花为O(m+n).

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac。

三.源码

from collections import Counter
class Solution:
    def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
        no_app,rst=[],[]
        num2cnt=Counter(arr1)
        for num in arr2:
            rst.extend(num2cnt[num]*[num])
            del num2cnt[num]
        for key in num2cnt:
            no_app.extend(num2cnt[key]*[key])
        rst.extend(sorted(no_app))
        return rst
            

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值