G面经prepare: set difference

时间:2024-01-09 10:56:50
给你A{1,2,3,4,4,5}, B{2,4},求A-B={1,3,4,5},很简单. visit 1

只用一个HashMap

 package TwoSets;
import java.util.*; public class Solution {
public ArrayList<Integer> findDiff(int[] arr1, int[] arr2) {
ArrayList<Integer> res = new ArrayList<Integer>();
HashMap<Integer, Integer> m1 = new HashMap<Integer, Integer>();
for (int item1 : arr1) {
if (!m1.containsKey(item1)) {
m1.put(item1, 1);
}
else {
m1.put(item1, m1.get(item1)+1);
}
}
for (int item2 : arr2) {
if (m1.containsKey(item2)) {
m1.put(item2, m1.get(item2)-1);
}
if (m1.get(item2) == 0) m1.remove(item2);
}
for (int elem : m1.keySet()) {
int num = m1.get(elem);
while (num > 0) {
res.add(elem);
num--;
}
}
return res;
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution sol = new Solution();
ArrayList<Integer> res = sol.findDiff(new int[]{1,2,3,4,4,5}, new int[]{2,4});
System.out.println(res);
} }