【leetcode】350. 两个数组的交集 II(python)

【leetcode】350. 两个数组的交集 II(python)_第1张图片

方法一:排序 + 双指针

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """     
        nums1.sort()     # sort, double index
        nums2.sort()
        res = []
        n1, n2 = len(nums1), len(nums2)
        i, j = 0, 0
        while i < n1 and j < n2:
            if nums1[i] == nums2[j]:
                res.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1
        return res

方法二:哈希表

import collections
class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """     
        # hashtable
        dic1 = collections.Counter(nums1)
        dic2 = collections.Counter(nums2)
        dic = dic1 & dic2
        res = []
        for i, num in enumerate(dic):
            while dic[num] > 0:
                res.append(num)
                dic[num] -= 1
        return res

你可能感兴趣的:(Python,Leetcode,python,双指针,哈希表)