349. Intersection of Two Arrays leetCode
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
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]
Explanation: [4,9] is also accepted.
Approach 1:
import java.util.*;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
// Step 1: Sort both arrays (Optional but helpful for two-pointer approach)
Arrays.sort(nums1);
Arrays.sort(nums2);
// Step 2: Use a HashSet to store the intersection (unique values only)
Set<Integer> set = new HashSet<>();
// Step 3: Initialize two pointers
int i = 0; // pointer for nums1
int j = 0; // pointer for nums2
int n1 = nums1.length;
int n2 = nums2.length;
// Step 4: Use two-pointer technique to find common elements
while (i < n1 && j < n2) {
if (nums1[i] == nums2[j]) {
// If both elements are equal, it's part of the intersection
set.add(nums1[i]);
i++;
j++;
} else if (nums1[i] < nums2[j]) {
// Move pointer i if nums1[i] is smaller
i++;
} else {
// Move pointer j if nums2[j] is smaller
j++;
}
}
// Step 5: Convert the Set to an array (required return type)
int[] result = new int[set.size()];
int k = 0;
for (int num : set) {
result[k++] = num;
}
// Step 6: Return the result array
return result;
}
}
Approach 2:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> resultSet = new HashSet<>();
// Add all elements from nums1 into set1
for (int num : nums1) {
set1.add(num);
}
// Check if nums2 elements exist in set1
for (int num : nums2) {
if (set1.contains(num)) {
resultSet.add(num);
}
}
// Convert resultSet to int array
int[] result = new int[resultSet.size()];
int i = 0;
for (int num : resultSet) {
result[i++] = num;
}
return result;
}
}
Comments
Post a Comment