Easy
809287FavoriteShare
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to nums2's size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
先排序法:
C++:
/*
* @Autor: SourDumplings
* @Date: 2019-09-14 10:13:30
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/intersection-of-two-arrays-ii/
*/
class Solution
{
public:
vector<int> intersect(vector<int> &nums1, vector<int> &nums2)
{
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int> res;
int j = 0;
int n1 = nums1.size(), n2 = nums2.size();
for (int i = 0; i < n1; i++)
{
while (j < n2 && nums2[j] < nums1[i])
++j;
if (j == n2)
{
break;
}
else if (nums2[j] == nums1[i])
{
res.push_back(nums2[j++]);
}
}
return res;
}
};
哈希表法:
Java:
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
/*
* @Autor: SourDumplings
* @Date: 2019-09-14 10:23:05
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/intersection-of-two-arrays-ii/
*/
class Solution
{
public int[] intersect(int[] nums1, int[] nums2)
{
Map<Integer, Integer> map1 = new Hashtable<>();
Map<Integer, Integer> map2 = new Hashtable<>();
for (int i : nums1)
{
if (map1.containsKey(i))
{
map1.replace(i, map1.get(i) + 1);
}
else
{
map1.put(i, 1);
}
}
for (int i : nums2)
{
if (map2.containsKey(i))
{
map2.replace(i, map2.get(i) + 1);
}
else
{
map2.put(i, 1);
}
}
Vector<Integer> temp = new Vector<>();
for (int i : map1.keySet())
{
if (map2.containsKey(i))
{
int n1 = map1.get(i);
int n2 = map2.get(i);
int n = n1 < n2 ? n1 : n2;
while (n-- > 0)
{
temp.add(i);
}
}
}
int n = temp.size();
int[] res = new int[n];
int i = 0;
for (int num : temp)
{
res[i++] = num;
}
return res;
}
}