LeetCode-给定两个数组,求它们的交集

题目链接

https://leetcode.com/problems/intersection-of-two-arrays-ii/

题目内容

    

给定两个数组,写一个方法来计算它们的交集。

一种思路

先遍历第一个数组,然后遍历第二个数组,寻找公共交集

# coding=utf-8
# @Date  :2018
# @Author    :shiwenzun
# @Language  :Python3.6
#给定两个数组,写一个方法来计算它们的交集。
class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        public_arry=[]
        for i in nums1:
            index =-1
            for j in range(0,len(nums2)):
                if nums2[j] == i:
                    index =  j
                    break
            if index != -1:
                public_arry.append(i)
                del nums2[index]
        return public_arry

思路二:先对第二个列表先排序,每次检查元素是否出现时用二分搜索

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        nums2.sort()
        for k in nums1:
            flag, j = self.binarySearch(nums2, k)
            if flag:
                res.append(k)
                del nums2[j]
        return res

    def binarySearch(self, nums, num):
        left = 0
        right = len(nums) - 1
        while left <= right:
            mid = (left + right) / 2
            if nums[mid] == num:
                return True, mid
            if nums[mid] < num:
                left = mid + 1
            else:
                right = mid - 1
        return False, 0

思路三 用字典存放nums1的值,和出现次数,然后和nums2进行对比

  def intersect1(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
       """
        res=[]
        temp={}
        for i in nums1:
            temp[i]=temp[i] + 1 if i in temp else 1
        for j in nums2:
            if j in temp and temp[j]>0:
                res.append(j)
                temp[j]=temp[j]-1
        return  res
if __name__ == '__mai

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值