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.
classSolution {
publicint[]intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
ArrayList<Integer> ansList =new ArrayList<Integer>();
for (int i = 0; i < nums1.length; i++) {
if (i == 0 || (i > 0 && nums1[i]!= nums1[i - 1])) {
if (Arrays.binarySearch(nums2, nums1[i]) >-1) {
ansList.add(nums1[i]);
}
}
}
int[] ans =newint[ansList.size()];
// Convert ArrayList to int array (and can't be used as a variable name)int k = 0;
for (int num: ansList) {
ans[k++]= num;
}
return ans;
}
}
⏰ Time complexity: O(m log m + n log n) where m and n is size of of nums1 and nums2. Mainly, for sorting two arrays and O(n log m) for searching elements elements in nums1 in nums2.