
Problem Statement
Given two integer arrays nums1 and nums2, the objective is to find the intersection of these two arrays. The term "intersection" in this context refers to elements that are present in both arrays. Crucially, if an element appears multiple times in both arrays, it should appear in the intersection array a number of times equal to the minimum number of times it appears in either array. The resultant intersection array can be returned in any order.
Examples
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.
Constraints
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 1000
Approach and Intuition
The given problem can be tackled effectively using the following steps:
- Use a hashmap to count the occurrences of each number in the first array (
nums1). - Initialize an empty list to store the intersecting elements.
- Iterate over the second array (
nums2) and for each element:- Check if the element is in the hashmap and has a non-zero count, which means it occurs in both arrays.
- If present, append it to the result list and decrement the count in the hashmap.
- This ensures that an element is added to the result list no more times than it appears in both arrays.
By using this approach, we can ensure that the intersection includes each element the minimum number of times it appears in both arrays. This method leverages hashmap for efficient lookup and count decrement operations, allowing us to optimize the solution for potentially large arrays while adhering to the constraints provided.
Solutions
- C++
- Java
vector<int> find_intersection(vector<int>& set1, vector<int>& set2) {
sort(begin(set1), end(set1));
sort(begin(set2), end(set2));
int a = 0, b = 0, c = 0;
while (a < set1.size() && b < set2.size()) {
if (set1[a] < set2[b]) {
++a;
} else if (set1[a] > set2[b]) {
++b;
} else {
set1[c++] = set1[a++];
++b;
}
}
return vector<int>(begin(set1), begin(set1) + c);
}
This summary outlines a solution for finding the intersection of two integer arrays set1 and set2. The solution is implemented in C++.
The function find_intersection starts by sorting both arrays set1 and set2. This facilitates the use of a two-pointer technique, which efficiently finds common elements. Here is a step-by-step breakdown of the process:
- Sort both input arrays,
set1andset2. - Initialize three integer variables
a,b, andcto serve as pointers and counters. - Run a while loop until one of the pointers
aorbexceeds the size ofset1orset2respectively.- If the current element in
set1is lesser than the current element inset2, increment pointerato move to the next element inset1. - If the current element in
set1is greater than the current element inset2, increment pointerbto move to the next element inset2. - If the elements at pointers
aandbare equal, it indicates a common element. Store this element inset1[c]and increment all pointersa,b, andc.
- If the current element in
- The loop terminates when the end of either array is reached. At this point, the common elements have been collected from the beginning up to the
c-th position inset1. - Construct a new vector from the first
celements ofset1to return only the intersected values.
This method is effective and efficient for finding intersected values between two arrays with minimal space usage by cleverly utilizing the input arrays for output.
public int[] findIntersection(int[] array1, int[] array2) {
Arrays.sort(array1);
Arrays.sort(array2);
int index1 = 0, index2 = 0, index3 = 0;
while (index1 < array1.length && index2 < array2.length) {
if (array1[index1] < array2[index2]) {
index1++;
} else if (array1[index1] > array2[index2]) {
index2++;
} else {
array1[index3++] = array1[index1++];
index2++;
}
}
return Arrays.copyOfRange(array1, 0, index3);
}
The provided Java solution implements a function to find the intersection of two arrays, where each element in the result should appear as many times as it shows in both arrays. The method, findIntersection, takes two integer arrays as input.
- Start by sorting both arrays. This ensures that identical elements are lined up, making comparison straightforward.
- Initialize three indices to zero:
index1forarray1,index2forarray2, andindex3for tracking the position inarray1to store intersecting elements. - Utilize a while loop to traverse both arrays until either of the arrays is completely processed. Inside the loop:
- Compare elements at the current index of both arrays:
- If the element in
array1is less than inarray2, incrementindex1to move to the next element inarray1. - If the element in
array1is more than inarray2, incrementindex2to move to the next element inarray2. - If the elements are equal, this means an intersection is found:
- Store the intersecting element in
array1at the current position ofindex3. - Increment both
index1andindex2to continue searching for other intersections. - Increment
index3to prepare a position for the next potential intersection.
- Store the intersecting element in
- If the element in
- Compare elements at the current index of both arrays:
- After exiting the loop, use
Arrays.copyOfRangeto extract the intersecting elements fromarray1, starting from the 0th index up toindex3. - Return the new array which contains all the intersecting elements.
This approach guarantees that the space complexity is handled efficiently by reusing array1 for the result storage, and the time complexity largely depends on the sorting process, making it O(n log n) due to the sorting of the arrays.