public class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int count = 0;
int length = A.length;
// create a hashmap saves the sum and numebr of times that sum appeared int A and B
HashMap<Integer, Integer> sum = new HashMap<Integer, Integer>();
// list all possible sums in A and B
for (int i=0; i<length; i++)
for (int j=0; j<length; j++) {
int tmp_sum = A[i]+B[j];
if (!sum.containsKey(tmp_sum))
sum.put(tmp_sum, 1);
else
// if sum exists in the map, increase the count
sum.put(tmp_sum, sum.get(tmp_sum)+1);
}
// list all possible sum in C and D
// if sum is the opposit value of the sum in map, add map's value to count
for (int i=0; i<length; i++)
for (int j=0; j<length; j++) {
int tmp_sum = C[i]+D[j];
// found a solution, add it count
if (sum.containsKey(-tmp_sum))
count += sum.get(-tmp_sum);
}
return count;
}
}
Leetcode 454. 4Sum II
最新推荐文章于 2021-12-25 19:07:23 发布