Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
- // A map to map all possible sum of elements in C and D to their count
- Map<Integer, Integer> m = new HashMap<>();
- for (int i = 0; i < C.length; i++) {
- for (int j = 0; j < D.length; j++) {
- int sum = C[i] + D[j];
- // Update counter
- // One more pair that adds up to sum
- m.put(sum, m.getOrDefault(sum, 0) + 1);
- }
- }
- // Going through A and B, if find A[i] + B[j] equals to -sum,
- // meaning we found a pair of A,B and can pair with all counts
- // of C, D that adds up to sum
- int result = 0;
- for (int i = 0; i < A.length; i++) {
- for (int j = 0; j < B.length; j++) {
- int sum = A[i] + B[j];
- result += m.getOrDefault(-sum, 0);
- }
- }
- return result;
- }
- }
Add Comment
Please, Sign In to add comment