Java, hashmap solution


  • 0
    C
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
    	        Arrays.sort(A);
    	        Arrays.sort(B);
    	        Arrays.sort(C);
    	        Arrays.sort(D);
    	        Map<Integer, Integer> first = new HashMap<>();
    	        Map<Integer, Integer> second = new HashMap<>();
    	        for(int i = 0; i < A.length; i++){
    	            for(int j = 0; j < B.length; j++){
    	                int val = A[i]+B[j];
    	                first.put(val, first.getOrDefault(val,0)+1);
    	            }
    	        }
    	        for(int i = 0; i < A.length; i++){
    	            for(int j = 0; j < B.length; j++){
    	                int val = C[i]+D[j];
    	                second.put(val, second.getOrDefault(val,0)+1);
    	            }
    	        }
    	        int count = 0;
    	        for(int key : first.keySet()){
    	            if(second.containsKey(0-key)){
    	                count += first.get(key)*second.get(-key);
    	            }
    	        }
    	        return count;
    	    }

  • 0
    D

    To be honest, I was quite surprised your method would be AC. I used 2 maps but got Memory Limit Exceeded. Mine is the same as yours except that I didn't sort array at first. I was wondering why sort would make such a difference.


  • 1
    C

    @DreamSeason
    To be honest, I was also surprised my method can get AC..... I don't know why sort would make difference....sorry.


Log in to reply
 

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