LeetCode Intersection of Two Arrays

时间:2023-03-08 22:03:27

原题链接在这里:https://leetcode.com/problems/intersection-of-two-arrays/

题目:

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2].

Note:

    • Each element in the result must be unique.
    • The result can be in any order.

题解:

用一个HashSet 来保存nums1的每个element.

再iterate nums2, 若HashSet contains nums2[i], 把nums2[i]加到res中,并把nums[i]从HashSet中remove掉.

Time Complexity: O(nums1.length + nums2.length). Space: O(nums1.length).

AC Java:

 public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> nums1Hs = new HashSet<Integer>();
for(int num : nums1){
nums1Hs.add(num);
} List<Integer> res = new ArrayList<Integer>();
for(int num : nums2){
if(nums1Hs.contains(num)){
res.add(num);
nums1Hs.remove(num);
}
}
int [] resArr = new int[res.size()];
int i = 0;
for(int num : res){
resArr[i++] = num;
}
return resArr;
}
}

也可以使用两个HashSet.

Time Complexity: O(nums1.length + nums2.length). Space: O(nums1.length).

AC Java:

 public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> nums1Hs = new HashSet<Integer>();
HashSet<Integer> intersectHs = new HashSet<Integer>();
for(int num : nums1){
nums1Hs.add(num);
}
for(int num : nums2){
if(nums1Hs.contains(num)){
intersectHs.add(num);
}
} int [] res = new int[intersectHs.size()];
int i = 0;
for(int num : intersectHs){
res[i++] = num;
}
return res;
}
}

Sort nums1 and nums2, 再用双指针 从头iterate两个sorted array.

Time Complexity: O(nlogn). Space: O(1).

AC Java:

 public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
HashSet<Integer> hs = new HashSet<Integer>();
int i = 0;
int j = 0;
while(i<nums1.length && j<nums2.length){
if(nums1[i] < nums2[j]){
i++;
}else if(nums1[i] > nums2[j]){
j++;
}else{
hs.add(nums1[i]);
i++;
j++;
}
} int [] resArr = new int[hs.size()];
int k = 0;
for(int num : hs){
resArr[k++] = num;
}
return resArr;
}
}

sort nums1, 然后nums2 array 每一个element在 sorted 上做binary search.

Time Complexity: O(mlogm + nlogm), m = nums1.length, n = nums2.length.

Space: O(resArr.length).

AC Java:

 public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> res = new HashSet<Integer>();
Arrays.sort(nums1);
for(int num : nums2){
if(binarySearch(nums1, num)){
res.add(num);
}
} int [] resArr = new int[res.size()];
int i = 0;
for(int num : res){
resArr[i++] = num;
}
return resArr;
} private boolean binarySearch(int [] nums, int target){
int low = 0;
int high = nums.length-1;
while(low <= high){
int mid = low + (high-low)/2;
if(nums[mid] < target){
low = mid+1;
}else if(nums[mid] > target){
high = mid-1;
}else{
return true;
}
}
return false;
}
}

跟上Intersection of Two Arrays IIIntersection of Three Sorted Arrays.