给你A{1,2,3,4,4,5}, B{2,4},求A-B={1,3,4,5},很简单. visit 1
只用一个HashMap
1 package TwoSets; 2 import java.util.*; 3 4 public class Solution { 5 public ArrayList<Integer> findDiff(int[] arr1, int[] arr2) { 6 ArrayList<Integer> res = new ArrayList<Integer>(); 7 HashMap<Integer, Integer> m1 = new HashMap<Integer, Integer>(); 8 for (int item1 : arr1) { 9 if (!m1.containsKey(item1)) { 10 m1.put(item1, 1); 11 } 12 else { 13 m1.put(item1, m1.get(item1)+1); 14 } 15 } 16 for (int item2 : arr2) { 17 if (m1.containsKey(item2)) { 18 m1.put(item2, m1.get(item2)-1); 19 } 20 if (m1.get(item2) == 0) m1.remove(item2); 21 } 22 for (int elem : m1.keySet()) { 23 int num = m1.get(elem); 24 while (num > 0) { 25 res.add(elem); 26 num--; 27 } 28 } 29 return res; 30 } 31 32 33 /** 34 * @param args 35 */ 36 public static void main(String[] args) { 37 // TODO Auto-generated method stub 38 Solution sol = new Solution(); 39 ArrayList<Integer> res = sol.findDiff(new int[]{1,2,3,4,4,5}, new int[]{2,4}); 40 System.out.println(res); 41 } 42 43 }
时间: 2024-11-10 14:21:31