LeetCode 349. Intersection of Two Arrays
write a function to determine the intersection between those two arrays.
and remember no duplicate allowed in the final results.
idea:
of course, we can use I two hashset to solve this problem.
and we can sort them, and use two pointer. and use one hashset.
but how can we solve this using binary search?
in order to use binary search you have to make the array sorted.
but we don;t have to get two arrays both sorted. so instead, we sort one, and then, for each of the other unsorted array, we binary search in that sorted array, and if we find it, we can just add them to set, and we convert the set to int[].
and this method will reduce the time complexity to O(nlogn)
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
HashSet<Integer> set = new HashSet<>();
for (int num: nums2) {
if (binarySearch(num, nums1)) {
set.add(num);
}
}
int[] res = new int[set.size()];
int i = 0;
for (Integer num: set) {
res[i++] = num;
}
return res;
}
private boolean binarySearch(int target, int[] nums) {
int l = 0;
int r = nums.length - 1;
while (l <= r) {
int mid = (r - l) / 2 + l;
if (nums[mid] == target) {
return true;
} else if (nums[mid] > target) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return false;
}
}

浙公网安备 33010602011771号