Given two arrays, write a function to compute their intersection.
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0, j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
++i;
}
else if (nums1[i] > nums2[j]) {
++j;
}
else {
set.add(nums1[i]);
++i;
++j;
}
}
int[] res = new int[set.size()];
int index = 0;
for (int e : set) {
res[index++] = e;
}
return res;
}
}
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> set = new HashSet<>();
Arrays.sort(nums2);
for (int i = 0; i < nums1.length; i++) {
int index = binarySearch(nums2, nums1[i]);
if (index != -1) {
set.add(nums1[i]);
}
}
int[] res = new int[set.size()];
int index = 0;
for (int e : set) {
res[index++] = e;
}
return res;
}
public int binarySearch(int[] nums, int target) {
int start = 0, end = nums.length - 1, mid = 0;
while (start <= end) {
mid = start + (end - start) / 2;
if (nums[mid] == target) {
return mid;
}
else if (nums[mid] < target) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return -1;
}
}
3. Time & Space Complexity