350. Intersection of Two Arrays II -- 双指针、哈希表、排序、二分搜索

来源:互联网 发布:python 毫秒级时间戳 编辑:程序博客网 时间:2024/05/21 10:21

350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]

解1:双指针,并把结果添加到栈中。

class Solution(object):    def intersect(self, nums1, nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: List[int]        """        nums1.sort()        nums2.sort()        p1 = 0        p2 = 0        ans = []        while (p1 < len(nums1)) and (p2 < len(nums2)):            if nums1[p1] == nums2[p2]:                ans.append(nums1[p1])                p1 += 1                p2 += 1            elif nums1[p1] < nums2[p2]:                p1 += 1            else:                p2 += 1        return ans

解2:
哈希表,首先把nums1的字符添加到哈希表中,然后遍历nums2,找到一个nums1中有的数并且计数大于0,就添加到放回的列表中,并且计数减去1.

class Solution(object):    def intersect(self, nums1, nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: List[int]        """        ans = []        d = {}        for num in nums1:            d[num] = d[num] + 1 if num in d else 1        for j in nums2:            if j in d and d[j] > 0:                ans.append(j)                d[j] -= 1        return ans