Leetcode POTD - Intersection of Two Arrays II
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.
Solution:
This implementation sorts both arrays first and then uses a two-pointer technique to find the intersection elements.
The
ranges::sort
function sorts bothnums1
andnums2
in non-decreasing order. Sorting the arrays helps simplify the process of finding the intersection by allowing a linear scan to identify common elements
ranges::sort(nums1);
ranges::sort(nums2);
result
is the result vector that will store the intersection elements.i
is an index variable for iterating throughnums1
.j
is an index variable for iterating throughnums2
.
vector<int> result;
int i = 0;
int j = 0;
- This
while
loop continues as long as there are elements to compare in bothnums1
andnums2
.if (nums1[i] < nums2[j])
: If the current element innums1
is less than the current element innums2
, incrementi
. This means the element innums1
cannot be in the intersection, so we move to the next element innums1
.else if (nums1[i] > nums2[j])
: If the current element innums1
is greater than the current element innums2
, incrementj
. This means the element innums2
cannot be in the intersection, so we move to the next element innums2
.else
: If the current elements innums1
andnums2
are equal, it means we have found a common element. We add this element toresult
and increment bothi
andj
to move to the next elements in both arrays.
while(i<nums1.size() && j<nums2.size()){
if(nums1[i] < nums2[j]){
++i;
}
else if(nums1[i] > nums2[j]){
++j;
}
else{
result.push_back(nums1[i]);
++i;
++j;
}
}
- Finally, the method returns the
result
vector containing the intersection ofnums1
andnums2
.
return result;
- Here is the entire code:
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
ranges::sort(nums1);
ranges::sort(nums2);
vector<int> result;
int i=0;
int j = 0;
while(i<nums1.size() && j<nums2.size()){
if(nums1[i] < nums2[j]){
++i;
}
else if(nums1[i] > nums2[j]){
++j;
}
else{
result.push_back(nums1[i]);
++i;
++j;
}
}
return result;
}
};
Thank you ! Keep Learning :))