题目描述:
给定两个数组求他们的公共部分,输出形式是数组,相同的元素累计计数
例如:
nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
原文描述:
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.
思路:
- 使用HashMap(Integer,Integer)的数据结构,首先遍历Array1
- 遍历Array2,如果Array1包含,而且get(key)的value减一还大于0,就继续
代码:
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> resultMap = new HashMap<Integer, Integer>(); ArrayList<Integer> list = new ArrayList<Integer>(); 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 j = 0; j < nums2.length; j++) { if (map.containsKey(nums2[j]) && map.get(nums2[j]) > 0) { map.put(nums2[j], map.get(nums2[j]) - 1); if (!resultMap.containsKey(nums2[j])) { resultMap.put(nums2[j], 1); } else { resultMap.put(nums2[j], resultMap.get(nums2[j]) + 1); } } } int sum = 0; for (Integer e : resultMap.keySet()) { int count = resultMap.get(e); sum += count; for (int i = 0; i < count; i++) { list.add(e); } } int[] result = new int[sum]; for (int i = 0; i < sum; i++) { result[i] = (int) list.get(i); } return result;