**Question:**
Given two arrays, write a function to compute their intersection.
**Example:**
nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
@Test
public void test() {
int[] nums1 = { 1 };
int[] nums2 = { 1, 1 };
this.intersect(nums1, nums2);
}
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
List<Integer> result = new ArrayList<>();
if (nums1.length < 1 || nums2.length < 1) {
return new int[] {};
} else {
for (int i = 0; i < nums1.length; i++) {
if (map.containsKey(nums1[i]))
map.put(nums1[i], map.get(nums1[i]) + 1);
else
map.put(nums1[i], 1);
}
for (int i = 0; i < nums2.length; i++) {
if (map.containsKey(nums2[i]) && map.get(nums2[i]) > 0) {
result.add(nums2[i]);
map.put(nums2[i], map.get(nums2[i]) - 1);
}
}
}
int num[] = new int[result.size()];
for (int i = 0; i < num.length; i++) {
num[i] = result.get(i);
}
return num;
}
leetcode-350 Intersection of Two Arrays II 求两个数组的交集 面试见到了吗?
最新推荐文章于 2024-11-05 19:36:08 发布