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.
解题思路
首先用map存储数组1里出现的元素,然后检查这些元素是否也在数组2中存在,如果存在则将该元素添加到返回的数组中。
实现代码
// Runtime: 8 ms
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums1) {
map.put(num, 1);
}
int len = 0;
for (int num : nums2) {
if (map.containsKey(num) && map.get(num) == 1) {
map.put(num, 2);
++len;
}
}
int[] nums = new int[len];
int i = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == 2) {
nums[i++] = entry.getKey();
}
}
return nums;
}
}