LeetCode350:Intersection of Two Arrays II(优化)

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

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?

LeetCode:链接

其实就是优化349题。不过这题是尽可能多的返回重复的数字。

第一种方法:用字典统计第一个列表都出现了哪些数及出现的次数,然后顺序遍历第二个列表,发现同时出现的数则加入到结果列表中,同时将第一个列表中相应的出现次数减一。

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

        return res

第二种方法:排序加双指针。

class Solution(object):
    def sort(self, nums, start, end):
        if end <= start:
            return start 
        index1, index2 = start, end 
        base = nums[start]
        while start < end:
            while start < end and nums[end] >= base:
                end -= 1
            nums[start] = nums[end]
            while start < end and nums[start] <= base:
                start += 1
            nums[end] = nums[start]
        nums[start] = base
        self.sort(nums, index1, start-1)
        self.sort(nums, start+1, index2)

    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        self.sort(nums1, 0, len(nums1)-1)
        self.sort(nums2, 0, len(nums2)-1)
        i, j = 0, 0
        res = []
        while i < len(nums1) and j < len(nums2):
            if nums1[i] < nums2[j]:
                i += 1
            elif nums1[i] > nums2[j]:
                j += 1
            else:                
                res.append(nums1[i])
                i += 1
                j += 1
        return res 

Follow Up

Q1: What if the given array is already sorted? How would you optimize your algorithm?

A: 采用solution 2

Q2: What if nums1's size is small compared to nums2's size? Which algorithm is better?

A: 如果nums1相对于nums2非常小,那么把nums1做成哈希表,哈希表占用空间更小

Q3: 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?

A:如果只有nums2不能放在内存中,则将nums1做成哈希表,nums2分批加载到内存中处理。(If only nums2 cannot fit in memory, put all elements of nums1 into a HashMap, read chunks of array that fit into the memory, and record the intersections.)

如果nums1和nums2都很大,都不适合储存在内存,那么就用外部排序分别来sort它们。将每2G(举例)读入内存,使用2指针技术,然后从内存中读取更多的2G。重复此操作,直到没有更多数据从磁盘读取。(If both nums1 and nums2 are so huge that neither fit into the memory, sort them using external sort, read (let’s say) 2G of each into memory and then using the 2 pointer technique, then read 2G more from the array that has been exhausted. Repeat this until no more data to read from disk.)

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84136237