解题思路:
将四个变成两两相加的和的两个集合,第一个集合是A和B的元素两两相加的结果,第二个集合是C和D的元素两两相加的所有结果,然后判断是否相加等于零,统计个数即可。
用列表来解题
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
first_set = []
second_set = []
for x in A:
for y in B:
first_set.append(x + y)
for x in C:
for y in D:
second_set.append(x + y)
first_set = sorted(first_set)
second_set = sorted(second_set)
ptr1 = 0
ptr2 = len(second_set) - 1
res = 0
while ptr1 < len(first_set) and ptr2 >= 0:
if first_set[ptr1] + second_set[ptr2] == 0:
first = 1
second = 1
while ptr1 != (len(first_set) - 1) and first_set[ptr1] == first_set[ptr1 + 1]:
first += 1
ptr1 += 1
while ptr2 != 0 and second_set[ptr2] == second_set[ptr2 - 1]:
second += 1
ptr2 -= 1
res += first * second
ptr1 += 1
elif first_set[ptr1] + second_set[ptr2] < 0:
ptr1 += 1
elif first_set[ptr1] + second_set[ptr2] > 0:
ptr2 -= 1
else:
print('something wrong!')
return res
用dict来解题
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
first_dict = {}
second_dict = {}
for x in A:
for y in B:
if x+y in first_dict:
first_dict[x + y] += 1
else:
first_dict[x + y] = 1
for x in C:
for y in D:
if x+y in second_dict:
second_dict[x + y] += 1
else:
second_dict[x + y] = 1
res = 0
first_set = sorted(list(first_dict.keys()))
second_set = sorted(list(second_dict.keys()))
ptr1 = 0
ptr2 = len(second_set) - 1
while ptr1 < len(first_set) and ptr2 >= 0:
if first_set[ptr1] + second_set[ptr2] == 0:
res += first_dict[first_set[ptr1]] * second_dict[second_set[ptr2]]
ptr1 += 1
elif first_set[ptr1] + second_set[ptr2] < 0:
ptr1 += 1
elif first_set[ptr1] + second_set[ptr2] > 0:
ptr2 -= 1
else:
print('something wrong!')
return res