leetcode笔记--Intersection of Two Arrays I & II



Intersection of Two Arrays

题目:难度(Easy)

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.
Tags:Binary Search, Hash Table, Two Pointers, Sort

分析:注意:交集结果中元素不能重复,但元素的顺序不care

法1:先排序,再归并,时间复杂度是O(nlogn),n=max(m,n)

代码实现:

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        注意:交集结果中元素不能重复,但元素的顺序不care
        """
        #return list(set(nums1)&set(nums2))#AC
        #法1:先排序,再归并,时间复杂度是O(nlogn),n=max(m,n)
        nums1.sort()
        nums2.sort()
        m, n = len(nums1), len(nums2)
        if m == 0 or n == 0:#交集,有一个为空,则结果为空
            return []
        
        result = []
        i, j, k = 0, 0, 0#k指向结果集result
        while i<m and j<n:
            if nums1[i] < nums2[j]:
                i += 1
            elif nums1[i] > nums2[j]:
                j += 1
            else:#==
                if k > 0 and result[-1] == nums1[i]:#重复,则不加入结果集中
                    pass
                else:
                    result.append(nums1[i])
                    k += 1
                i += 1
                j += 1
        return result


法2:hashtable,时间复杂度是O(m+n)

代码实现:

def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        m, n = len(nums1), len(nums2)
        if m == 0 or n == 0:#交集,有一个为空,则结果为空
            return []
            
        from collections import defaultdict
        hash = defaultdict(int)#记录在nums1中每个元素是否出现
        for num in nums1:
            hash[num] = 1
            
        result = []
        for num in nums2:
            if hash[num]!=0:
                result.append(num)
                hash[num] = 0
        return result


参考:http://blog.csdn.net/kakitgogogo/article/details/51444224

Intersection of Two Arrays II

题目:难度(Easy)

Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Tags:Binary Search, Hash Table, Two Pointers, SortTags

分析:与Intersection of Two ArraysI相比,结果集中要保留重复元素

法1:先排序,再归并,时间复杂度是O(nlogn),n=max(m,n)

代码实现:

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        与Intersection of Two ArraysI相比,结果集中要保留重复元素
        """
        #法1:先排序,再归并,时间复杂度是O(nlogn),n=max(m,n)
        nums1.sort()
        nums2.sort()
        m, n = len(nums1), len(nums2)
        if m == 0 or n == 0:#交集,有一个为空,则结果为空
            return []
        
        result = []
        i, j = 0, 0
        while i<m and j<n:
            if nums1[i] < nums2[j]:
                i += 1
            elif nums1[i] > nums2[j]:
                j += 1
            else:#==
                result.append(nums1[i])
                i += 1
                j += 1
        return result

法2:hashtable,时间复杂度是O(m+n)

代码实现:

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        m, n = len(nums1), len(nums2)
        if m == 0 or n == 0:#交集,有一个为空,则结果为空
            return []
        if m > n:
            nums1, nums2 = nums2, nums1#nums1总是较短的那个
            
        from collections import Counter
        hash = Counter(nums1)#记录在nums1中每个元素是否出现
        #注意:当引用Counter类型的字典一个不存在的键时返回0而不是抛出一个KeyError
        result = []
        for num in nums2:
            if hash[num]>0:
                result.append(num)
                hash[num] -= 1
        return result

Follow up:

1.如果数组已经有序,那么使用双指针实现“归并”,时间复杂度是O(m+n)

2.如果nums1相对于nums2非常小,那么把nums1做成hash表,hash表占用空间更小

3.同样把num1做成哈希表,nums2分批加载到内存中处理。

参考:

http://bookshadow.com/weblog/2016/05/21/leetcode-intersection-of-two-arrays-ii/

http://www.cnblogs.com/Liok3187/p/5517848.html



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值