548.Intersection of Two Arrays I
2017-07-23 本文已影响0人
博瑜
public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
// Write your code here
Map<Integer,Integer> map = new HashMap<>();
int length1 = nums1.length;
for (int i = 0; i < length1; i++) {
if (map.containsKey(nums1[i])) {
map.put(nums1[i], map.get(nums1[i]) + 1);
} else {
map.put(nums1[i], 1);
}
}
ArrayList<Integer> list = new ArrayList<>();
int length2 = nums2.length;
for (int i = 0; i < length2; i++) {
if (map.containsKey(nums2[i])) {
list.add(nums2[i]);
if (map.get(nums2[i]) == 1) map.remove(nums2[i]);
else map.put(nums2[i], map.get(nums2[i]) - 1);
}
}
int length = list.size();
int[] result = new int[length];
for (int i = 0; i < length; i++) {
result[i] = list.get(i);
}
return result;
}
}