[easy+][Array][Two-pointers]350. Intersection of Two Arrays II

原题是:

Given two arrays, write a function to compute their intersection.

***: 349.是该题的简单版本,区别是结果不需要返回重复的结果。
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?

思路:

这个题有两个标准解法:
1.是我代码所写的two pointer方法。先将两个数组排序,然后两指针分别比较对应位置。谁大了,挪动另一个指针。相等则把该元素插入结果中。
2.用hash table 存第一个数组的元素对应元素出现的个数。再遍历第二个数组,对于hashtable中已有的Key,填入结果,并将value值减去1。

对follow-up:
3.如果内存不够,那只能用哈希的方法,第二个数组分批载入。而第一个方法,由于需要排序,无法分批载入数组。

代码是:

class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        i,j = 0,0
        num1 = sorted(nums1)
        num2 = sorted(nums2)
        res = []
        
        while i < len(num1) and j < len(num2):
            if num1[i] < num2[j]:
                i += 1
            elif num1[i] > num2[j]:
                j += 1
            else:
                res.append(num1[i])
                i += 1
                j += 1
        return res
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 感恩冥想 1、感恩哥哥早晨起来帮助我给叔叔阿姨送早餐,让我有足够的时间去洗头发整理我的衣物参加辟谷 2、感恩冠晴姐...
    栾宜阅读 276评论 0 0
  • 今天下了很大的雨,虽然不及小时候某年夏天的暴雨。和昨天一样,大早上挣扎着起床,为了半天50块钱的工资。心中有一瞬间...
    青五阅读 264评论 0 0
  • 无论是权威的PGC的时代, 还是大众热的UGC的当下。 都存在的实事就是创造优质到极致! 知识变现的年代:追求的是...
    庐陵居士赵氏兄阅读 117评论 0 0