G面经prepare: set difference
set 面经 Difference prepare
2023-09-11 14:14:07 时间
给你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 }
相关文章
- [Android Studio] Android Studio如何快速生成get,set,tostring,构造函数
- java:Set对象TreeSet有序子类,HashSet无序子类,重复对象二
- R abalone data set
- [ES6] Set && WeakSet
- [Bash] Set Default Arguments with Bash Shell Parameter Expansions
- [Angular] Omit relative path by set up in tsconfig.json
- 【异常】File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
- Error attempting to get column ‘xxx‘ from result set. Cause: java.sql.SQLDataException错误的解决方法
- nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping错误的决方法
- ZOJ Problem Set - 3819Average Score
- ubuntu下一个jboss-seam-2.2.2.Final/examples/build.xml:754: warning: 'includeantruntime' was not set
- 一种是CI(Constructor Injection)构造方法注入,另一种是SI(Set Injection) set 注入
- ini_set的权限大于error_reporting