Java solution sharing


  • 0
    L
    public class Solution {
        public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
            Map<Integer, Integer> firstHalf = new HashMap<>();
            Map<Integer, Integer> secondHalf = new HashMap<>();
            
            twoSum(A, B, firstHalf);
            twoSum(C, D, secondHalf);
            
            int result = 0;
            for (Integer x : firstHalf.keySet()){
                if (secondHalf.containsKey(-x)){
                    result = result + (firstHalf.get(x)*secondHalf.get(-x));
                }
            }
            return result;
        }
        
        private void twoSum(int[] first, int[] second, Map<Integer, Integer> record){
            for (int i=0; i<first.length; i++){
                for (int j=0; j<second.length; j++){
                    int sum = first[i] + second[j];
                    Integer count = record.get(sum);
                    if (count == null){
                        record.put(sum, 1);
                    }
                    else {
                        record.put(sum, count+1);
                    }
                }
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.