Guest User

Untitled

a guest
Feb 19th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. class Solution {
  2. public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
  3. // A map to map all possible sum of elements in C and D to their count
  4. Map<Integer, Integer> m = new HashMap<>();
  5.  
  6. for (int i = 0; i < C.length; i++) {
  7. for (int j = 0; j < D.length; j++) {
  8. int sum = C[i] + D[j];
  9.  
  10. // Update counter
  11. // One more pair that adds up to sum
  12. m.put(sum, m.getOrDefault(sum, 0) + 1);
  13. }
  14. }
  15.  
  16. // Going through A and B, if find A[i] + B[j] equals to -sum,
  17. // meaning we found a pair of A,B and can pair with all counts
  18. // of C, D that adds up to sum
  19. int result = 0;
  20.  
  21. for (int i = 0; i < A.length; i++) {
  22. for (int j = 0; j < B.length; j++) {
  23. int sum = A[i] + B[j];
  24.  
  25. result += m.getOrDefault(-sum, 0);
  26. }
  27. }
  28.  
  29. return result;
  30. }
  31. }
Add Comment
Please, Sign In to add comment