leetcode__四数相加II__python

解题思路:

将四个变成两两相加的和的两个集合,第一个集合是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
                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值