Intersection of Two Arrays
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0)
return new int[0];
Arrays.sort(nums1);
HashSet<Integer> set = new HashSet<>();
for(int i = 0 ; i < nums2.length; i++){
if(binarySearch(nums1,nums2[i])){
//
set.add(nums2[i]);
}
}
int[] res = new int[set.size()];
int i = 0;
for(Iterator<Integer> it = set.iterator(); it.hasNext(); ){
res[i] = it.next();
i++;
}
return res;
}
public boolean binarySearch(int[] nums,int target){
int start = 0, end = nums.length - 1;
while(start + 1 < end){
int mid = start + (end - start)/2;
if(nums[mid] == target){
return true;
}
if(nums[mid] > target){
end = mid;
}else{
start = mid;
}
}
if(nums[start] == target || nums[end] == target){
return true;
}
return false;
}
}Last updated