leetcode349

来源:互联网 发布:管家婆软件使用感想 编辑:程序博客网 时间:2024/05/24 06:34

349 easy Intersection of Two Arrays
*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.*
我是这样写的:

class Solution(object):    def intersection(self, nums1, nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: List[int]        """        l=[]        for num in nums1:            if num in nums2 and num not in l:                l.append(num)        return l
           然后在Discuss中看到有人居然只用了一句话!!!(好��)
return [x for x in set(nums1) if x in set(nums2)]

总结点呢 就是:set可以除重复 这要写巧妙的避开了是否重复的判断
;还有就是使用列表生成简单了很多。

0 0
原创粉丝点击