-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFourSum.java
More file actions
34 lines (30 loc) · 950 Bytes
/
FourSum.java
File metadata and controls
34 lines (30 loc) · 950 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package leetcode.array;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName FourSum
* @Description 四数相加 https://leetcode-cn.com/problems/4sum-ii/
* @Author changxuan
* @Date 2020/11/27 下午10:56
**/
public class FourSum {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> map = new HashMap<>();
//Map<Integer, Integer> map = new HashMap<>();
int res = 0;
for(int i = 0;i<A.length;i++){
for(int j= 0;j<B.length;j++){
int sumAB = A[i]+B[j];
if(map.containsKey(sumAB)) map.put(sumAB,map.get(sumAB)+1);
else map.put(sumAB,1);
}
}
for(int i = 0;i<C.length;i++){
for(int j = 0;j<D.length;j++){
int sumCD = -(C[i]+D[j]);
if(map.containsKey(sumCD)) res += map.get(sumCD);
}
}
return res;
}
}