350. Intersection of Two Arrays II

问题描述
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

遍历一个数组,将所有元素添加到哈希表中。
遍历第二个数组,如果在哈希表中则添加到数组中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
ArrayList<Integer> arr = new ArrayList<Integer>();
int count = 0;

for ( int i = 0 ; i < nums1.length ; i++ ){
if (!map.containsKey(nums1[i])){
map.put(nums1[i],1);
}
else{
map.put(nums1[i],map.get(nums1[i])+1);
}

}

for ( int i = 0 ; i < nums2.length ; i++ ){
if (map.containsKey(nums2[i])){
if (map.get(nums2[i]) > 0){
count++;
arr.add(nums2[i]);
map.put(nums2[i],map.get(nums2[i])-1);
}
}
}
int[] ans = new int[count];

for (int i = 0 ; i < arr.size() ; i++){
ans[i] = arr.get(i);
}
return ans;
}
}
Author

Xander

Posted on

2022-04-04

Updated on

2022-04-10

Licensed under

Comments