(LeetCode)Intersection of Two Arrays --- 求交集

来源:互联网 发布:arp查看mac地址 编辑:程序博客网 时间:2024/06/10 03:22

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

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

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

Subscribe to see which companies asked this question

解题分析:

第一次用python写交集,本打算还用C/C++的方法,使用哈希。

python中的话可以使用set函数来去重。


代码一:

__author__ = 'jiuzhang'# -*- coding:UTF-8 -*-class Solution(object):    def intersection(self, nums1, nums2):        return list(set(nums1) & set(nums2))


代码二:

# -*- coding: UTF-8 -*-class Solution(object):    def intersection(self, nums1, nums2):        set1 = set(nums1)        ans = []        for x in nums2:            if x in set1:                ans += x                set1.remove(x)        return ans


0 0
原创粉丝点击