标签:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
Note:
Follow up:
两个map分别存储两个数组的元素出现次数,然后以最少出现次数决定是否出现在结果数组中以及出现在结果数组中的次数。
// Runtime: 13 ms
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
for (int num : nums1) {
if (map1.containsKey(num)) {
map1.put(num, map1.get(num) + 1);
} else {
map1.put(num, 1);
}
}
Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
for (int num : nums2) {
if (map2.containsKey(num)) {
map2.put(num, map2.get(num) + 1);
} else {
map2.put(num, 1);
}
}
List<Integer> list = new ArrayList<Integer>();
for (Map.Entry<Integer, Integer> entry : map1.entrySet()) {
int times = entry.getValue();
if (map2.containsKey(entry.getKey())) {
times = Math.min(times, map2.get(entry.getKey()));
} else {
times = 0;
}
for (int i = 0; i < times; i++) {
list.add(entry.getKey());
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}
[LeetCode] Intersection of Two Arrays II
标签:
原文地址:http://blog.csdn.net/foreverling/article/details/51470517