Leetcode #350 Intersection of Two Arrays II

Description

Given two arrays, write a function to compute their intersection.

Note

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Example

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Explain

扫一遍nums1,然后每个元素去nums2中寻找并去除,时间复杂度O(nm^2) n为nums1长度,m为nums2长度,题目中有几个Follow up:
- 如果是有序的,那么开两个位置指示器,nums1前进的时候看nums2的指示器数是否相同或小于nums1所指示的数,当然相同的时候要记录,然后向前进,这样复杂度是O(n+m)
- 如果nums1的长度小于nums2,那就扫nums2去找nums1,复杂度不变
- 如果数过多无法一次读到内存,开两个dict记录每个数次数,分次读完后再扫一遍

Code

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        ans = []
        for i in nums1:
            if i in nums2:
                ans.append(i)
                nums2.remove(i)
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值