Intersection of two arrays || (Riplocks | Elementary Algorithms | Arrays | Python)

1. Topic description

insert image description here

Two, code analysis

Solution 1: Sorting plus double pointer method

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

# solution = Solution()
# result = solution.intersect([4,4,5,9],[3,4,4,8,9,9])
# print(result)

Note: For ordered arrays , you can move closer to the direction of double pointers .

Solution 2: Hash table

from collections import Counter
class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        result = []
        nums1 = Counter(nums1)
        for i in nums2:
            if (i in nums1) and nums1[i]:
                result.append(i)
                nums1[i] = nums1[i]-1
        return result

# solution = Solution()
# result = solution.intersect([4,4,5,9],[3,4,4,8,9,9])
# print(result)

Since the same number may appear multiple times in both arrays, a hash table is required to store the number of occurrences of each number. For a number, the number of occurrences in the intersection is equal to the minimum number of occurrences of the number in the two arrays.

First traverse the first array, and record each number in the first array and the corresponding number of occurrences in the hash table, then traverse the second array, for each number in the second array, if in the hash table If the number exists in the hash table, add that number to the answer and decrement the number of occurrences of that number in the hash table.

In order to reduce the space complexity, first traverse the shorter array and record each number and the corresponding number of occurrences in the hash table, and then traverse the longer array to get the intersection.

The Counter() function in Python is a class in the collections module, which is used to count the number of occurrences of different elements in a string or list, and the return value is a dictionary .

3. Summary

The link to the official solution can be found here .

Guess you like

Origin blog.csdn.net/qq_40968179/article/details/128518662