Java O(n^2) solution practice


  • 0
    D
    public class Solution {
        public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
            Map<Integer, Integer> sumfreq = new HashMap<>();
            for (int a : A) {
                for (int b : B) {
                    int sum = a + b;
                    sumfreq.put(sum, sumfreq.containsKey(sum) ? sumfreq.get(sum) + 1 : 1);
                }
            }
            int count = 0;
            for (int c : C) {
                for (int d : D) {
                    int sum = c + d;
                    count += sumfreq.containsKey(-sum) ? sumfreq.get(-sum) : 0;
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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