1
+ ##==================================
2
+ ## Leetcode
3
+ ## Student: Vandit Jyotindra Gajjar
4
+ ## Year: 2020
5
+ ## Problem: 350
6
+ ## Problem Name: Intersection of Two Arrays II
7
+ ##===================================
8
+ #
9
+ #Given two arrays, write a function to compute their intersection.
10
+ #
11
+ #Example 1:
12
+ #
13
+ #Input: nums1 = [1,2,2,1], nums2 = [2,2]
14
+ #Output: [2,2]
15
+ #Example 2:
16
+ #
17
+ #Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
18
+ #Output: [4,9]
19
+ #Note:
20
+ #
21
+ #Each element in the result should appear as many times as it shows in both arrays.
22
+ #The result can be in any order.
23
+ class Solution :
24
+ def intersect (self , nums1 , nums2 ):
25
+ i , j , tmp = 0 , 0 , [] #Initialize i, j, and tmp
26
+ nums1 .sort (), nums2 .sort () #Sort nums1 and nums2
27
+ while i < len (nums1 ) and j < len (nums2 ): #Loop till condition reach
28
+ if nums1 [i ] == nums2 [j ]: #Condition-check: If nums1's i and nums2's j value is same
29
+ tmp .append (nums1 [i ]) #Then we append the value to tmp
30
+ i += 1 #Update i by increasing 1
31
+ j += 1 #Update j by increasing 1
32
+ elif nums1 [i ] < nums2 [j ]: #Condition-check: Elif nums1's i value is less than nums2's value
33
+ i += 1 #Update i by increasing 1
34
+ else : #Condition-check:Else
35
+ j += 1 #Update j by increasing 1
36
+ return tmp #Return updated tmp
0 commit comments