classSolution { publicintthreeSumMulti(int[] arr, int target) { //enumberate every element and put them into the map HashMap<Integer, Long> map = newHashMap<Integer, Long>(); longcount=0; for ( int num : arr ){ if (!map.containsKey(num)){ map.put(num, (long)1); } else{ map.put(num, map.get(num)+1); } } //traverse whole elements and select three numbers for ( int a : map.keySet() ){ longtotalA= map.get(a); for (int b : map.keySet()){ longtotalB= map.get(b); if ( a == b ){ if (totalB < 2){ continue; } totalB = totalB - 1; }
intc= target - a - b; if ( map.containsKey(c) ){ longtotalC= map.get(c); longtotal=0; if ( a == b && b == c ){ total = totalA * totalB * ( totalC - 2 ) ; } elseif ( b == c || a == c ){ total = totalA * totalB * ( totalC - 1 ) ; } else{ total = totalA * totalB * totalC; } if ( total > 0 ){ count += total; }