LeetCode 454. 四数相加 II 4Sum II

4-5 灵活选择键值 4Sum II

题目: LeetCode 454. 四数相加 II

A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

2

1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
import java.util.HashMap;

// 454. 4Sum II
// https://leetcode.com/problems/4sum-ii/description/
// 时间复杂度: O(n^2)
// 空间复杂度: O(n^2)
public class Solution1 {

public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {

if(A == null || B == null || C == null || D == null)
throw new IllegalArgumentException("Illegal argument");

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < C.length ; i ++)
for(int j = 0 ; j < D.length ; j ++){
int sum = C[i] + D[j];
if(map.containsKey(sum))
map.put(sum, map.get(sum) + 1);
else
map.put(sum, 1);
}

int res = 0;
for(int i = 0 ; i < A.length ; i ++)
for(int j = 0 ; j < B.length ; j ++)
if(map.containsKey(-A[i]-B[j]))
res += map.get(-A[i]-B[j]);

return res;
}

public static void main(String[] args) {

int[] a = {1, 2};
int[] b = {-2, -1};
int[] c = {-1, 2};
int[] d = {0, 2};
System.out.println((new Solution1()).fourSumCount(a, b, c, d));
}
}

import java.util.HashMap;

// 454. 4Sum II
// https://leetcode.com/problems/4sum-ii/description/
// 时间复杂度: O(n^2)
// 空间复杂度: O(n^2)
public class Solution2 {

public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {

if(A == null || B == null || C == null || D == null)
throw new IllegalArgumentException("Illegal argument");

HashMap<Integer, Integer> mapAB = new HashMap<Integer, Integer>();
for(int i = 0 ; i < A.length ; i ++)
for(int j = 0 ; j < B.length ; j ++){
int sum = A[i] + B[j];
if(mapAB.containsKey(sum))
mapAB.put(sum, mapAB.get(sum) + 1);
else
mapAB.put(sum, 1);
}

HashMap<Integer, Integer> mapCD = new HashMap<Integer, Integer>();
for(int i = 0 ; i < C.length ; i ++)
for(int j = 0 ; j < D.length ; j ++){
int sum = C[i] + D[j];
if(mapCD.containsKey(sum))
mapCD.put(sum, mapCD.get(sum) + 1);
else
mapCD.put(sum, 1);
}

int res = 0;
for(Integer sumab: mapAB.keySet()){
if(mapCD.containsKey(-sumab))
res += mapAB.get(sumab) * mapCD.get(-sumab);
}

return res;
}

public static void main(String[] args) {

int[] a = {1, 2};
int[] b = {-2, -1};
int[] c = {-1, 2};
int[] d = {0, 2};
System.out.println((new Solution2()).fourSumCount(a, b, c, d));
}
}


07-14 1183

09-24 48

03-01 355

07-06 105

07-02 17

05-26 2675

05-26 505

02-29 54

02-19 155

08-12 651

LeetCode 454. 四数相加 II(C++)

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。