原题链接:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
实现如下:
import java.util.*;
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(Arrays.toString(s.intersect(new int[]{1, 2, 2, 1}, new int[]{2, 2})));
}
public int[] intersect(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) {
return new int[0];
}
Map<Integer, Integer> map = new HashMap<>(nums1.length);
for (int i = 0; i < nums1.length; i++) {
map.put(nums1[i], map.getOrDefault(nums1[i], 0) + 1);
}
ArrayList<Integer> list = new ArrayList<>(nums2.length);
for (int i = 0; i < nums2.length; i++) {
if (map.containsKey(nums2[i]) && map.get(nums2[i]) > 0) {
list.add(nums2[i]);
map.put(nums2[i], map.get(nums2[i]) - 1);
}
}
int[] res = new int[list.size()];
int i = 0;
for (int item : list) {
res[i++] = item;
}
return res;
}
}