hashmap - Intersection of a Set with a twist Java -
so got following question in technical interview , thought pretty interesting.
given 2 arrays: = {1,2,2,4,5} , b = {1,2,6,} write code performs following 2 operations: a-b {2,4,5} , b-a {6}. meaning, find common element in other array , remove original. if b {1,2}, b-a {} since contains elements of b , b has no unique elements.
i solved question in following way, , hoping see if had suggestions on how possibly make better.
public static void main(string args[]) { map hashtable = new hashmap(); int a[] = {1,1,2,4,5,6,6}; int b[] = {1,2,6}; arraylist ba = new arraylist(); arraylist ab = new arraylist(); int[] occurances = new int[a.length]; //int occurances = 0; (int = 0; < a.length; i++) { occurances[a[i]]++; hashtable.put(a[i], occurances[a[i]]); } //system.out.println(arrays.tostring(occurances)); system.out.println(hashtable); //find ba (int = 0; < b.length; i++) { if(hashtable.containskey(b[i])) { occurances[b[i]]--; hashtable.put(b[i], occurances[b[i]]); } else ba.add(b[i]); } for(int = 0; <a.length; i++) { if(hashtable.containskey(a[i]) && occurances[a[i]] != 0) { ab.add(a[i]); occurances[a[i]]--; hashtable.put(a[i], occurances[a[i]]); } } system.out.println("ab = " + ab); system.out.println("ba =" + ba); } }
****edit***** mistakenly called arrays sets when posed question. since arrays can have duplicate elements, definition not sets. sorry confusion.
you can use set
have union , intersection functions.
integer a[] = {1, 2, 2, 4, 5}; integer b[] = {1, 2, 6}; public void test() { // grow 2 sets arrays. set<integer> sa = arrays.stream(a) .collect(collectors.tocollection(treeset::new)); set<integer> sb = arrays.stream(b) .collect(collectors.tocollection(treeset::new)); // make new 1 don't damage sa or sb. set<integer> sc = new hashset<>(sa); sc.removeall(sb); system.out.println(sa + " - " + sb + " = " + sc); set<integer> sd = new hashset<>(sb); sd.removeall(sa); system.out.println(sb + " - " + sa + " = " + sd); }
prints
[1, 2, 4, 5] - [1, 2, 6] = [4, 5] [1, 2, 6] - [1, 2, 4, 5] = [6]
Comments
Post a Comment