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.
First talk about my own (chicken dish) ideas: First, I would like to go heavy on the first array (nums1), then cycle to determine whether the value in nums2, some words, add new list.
Code for Example 1 as follows:
1 class Solution: 2 def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 num1 = set(nums1) 4 num = [i for i in num1 if i in nums2] 5 return num
There is also a method similar to Example 2:
1 class Solution: 2 def set_intersection(self, set1, set2): 3 return [x for x in set1 if x in set2] 4 5 def intersection(self, nums1, nums2): 6 """ 7 :type nums1: List[int] 8 :type nums2: List[int] 9 :rtype: List[int] 10 """ 11 set1 = set(nums1) 12 set2 = set(nums2) 13 14 if len(set1) < len(set2): 15 return self.set_intersection(set1, set2) 16 else: 17 return self.set_intersection(set2, set1)
But his running time:
Than I do fast 24ms, thought-provoking questions, complexity analysis,
-
Time complexity: O (m + n) O (m + n), where n and m is the length of the array. O (n) O (n) time for switching nums1 in the collection, O (m) O (m) nums2 time for switching to the collection, and the average case, a set of operations is O (1) O (1))
-
Space complexity: O (m + n) O (m + n), the worst case is that all elements in the array are different.
For omnipotent python, the built-intersection method, consider the following the procedures of Example 3:
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1 = set(nums1)
set2 = set(nums2)
return list(set2 & set1)
What is a bit speechless, to see if he's running time, although some slower speed than the above Example 2, but the code is simple and a lot of advantages and disadvantages.
Complexity analysis:
-
Time complexity: in general is O (m + n) O (m + n), the worst case is O (m \ times n) O (m × n).
-
Spatial complexity: the worst case is O (m + n) O (m + n), when all the elements in the array is not the same.
I can only say that is too much food. . . . . . . .
beginner
Share and success, your nemesis is me, remember that the quality of triple!
Source: stay button (LeetCode) link: https://leetcode-cn.com/problems/intersection-of-two-arrays