LeetCode 349- intersection of two arrays - simple

Subject description:

Given two arrays, write a function to compute their intersection.
 
Example 1:
 
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
 
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Description:
 
The output of each element must be unique.
We can not consider the order of output.
 
Source: stay button (LeetCode)
 

Problem-solving ideas:

1, brute force - one by one iterative calculation
 Time complexity of O (n * m)
 
2, using the hash table
1) Set the set of hash table structure to achieve, it does not allow collection of duplicate values
2) comparing two arrays, an array of individually checking whether the minimum to the maximum of the array, whether a time element in the other array is O (1)
Thanks to the use of collection
//Java
class Solution {
  public int[] set_intersection(HashSet<Integer> set1, HashSet<Integer> set2) 
{
    int [] output = new int[set1.size()];
    int idx = 0;
    for (Integer s : set1)//遍历数据set1
      if (set2.contains(s)) output[idx++] = s;//检查set2里是否包含set1,若包含则添加到新的数组里

    return Arrays.copyOf(output, idx);
  }

  public int[] intersection(int[] nums1, int[] nums2) 
  {
    HashSet<Integer> set1 = new HashSet<Integer>();//创建哈希表Set1
    for (Integer n : nums1) set1.add(n);
    HashSet<Integer> set2 = new HashSet<Integer>();//创建哈希表Set2
    for (Integer n : nums2) set2.add(n);
   //执行数据的交集操作
    if (set1.size() < set2.size()) return set_intersection(set1, set2);
    else return set_intersection(set2, set1);
  }
}

Algorithm complexity analysis:

Time complexity: O (n)

Space complexity: O (n)

//python3
class Solution:
    def set_intersection(self, set1, set2):
        return [x for x in set1 if x in set2]
        
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """  
        set1 = set(nums1)#集合1
        set2 = set(nums2)#集合2
        
        if len(set1) < len(set2):
            return self.set_intersection(set1, set2)
        else:
            return self.set_intersection(set2, set1)

 

Published 132 original articles · won praise 112 · views 90000 +

Guess you like

Origin blog.csdn.net/heda3/article/details/104033958