Python set 函数

  • 时间:
  • 来源:互联网
  • 文章标签:

Python set 函数 , Leetcode 349

    • My solution
    • Other solutions

set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

Leetcode:

349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

My solution


class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        common=[] 
        for p1 in nums1:
            try:
                if nums2.index(p1)!=None:
                    common.append(p1)
            except:
                continue
        return set(common)

Other solutions

  class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        set1 = set(nums1)
        set2 = set(nums2)
        
        return list(set1 & set2)

本文链接http://www.taodudu.cc/news/show-1944810.html