tutorialcup
Intersection of Two Arrays II Leetcode Solution
Problem Statement
In this problem two arrays are given and we have to find out the intersection of this two arrays and return the resultant array.
Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.
Example
nums1 = , nums2 =
nums1 = , nums2 =
Approach 1 (Using Hash map)
To find out the intersection of two arrays (nums1 and nums2) we can first store the count of each element of one array (let nums1) using a Hash map. Then we can traverse through the second array (nums2) and for each element in nums2 we would check if count of that element in nums1 is positive or not.
- if count of nums2 in array nums1 is positive, then add this element(nums2) in result array. And decrease the count of this element in Hash map.
- else this element is not to be added in result.
Note: we will store the elements of that array in hash map whose size is smaller so as to minimize the space complexity.
Implementation for Intersection of Two Arrays II Leetcode Solution
C++ Program
www.tutorialcup.com/leetcode-solutions/intersection-of-tw...
Intersection of Two Arrays II Leetcode Solution
Problem Statement
In this problem two arrays are given and we have to find out the intersection of this two arrays and return the resultant array.
Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.
Example
nums1 = , nums2 =
nums1 = , nums2 =
Approach 1 (Using Hash map)
To find out the intersection of two arrays (nums1 and nums2) we can first store the count of each element of one array (let nums1) using a Hash map. Then we can traverse through the second array (nums2) and for each element in nums2 we would check if count of that element in nums1 is positive or not.
- if count of nums2 in array nums1 is positive, then add this element(nums2) in result array. And decrease the count of this element in Hash map.
- else this element is not to be added in result.
Note: we will store the elements of that array in hash map whose size is smaller so as to minimize the space complexity.
Implementation for Intersection of Two Arrays II Leetcode Solution
C++ Program
www.tutorialcup.com/leetcode-solutions/intersection-of-tw...