[LeetCode By Python] 18. 4Sum

一、题目

[LeetCode By Python] 18. 4Sum_第1张图片
18. 4Sum

二、解题

用的和3Sum一样的解法。。只是多了一重循环

三、尝试与结果

class Solution(object):
    def fourSum(self, nums, target):
        resultList = []
        nums.sort()
        for i in range(0,len(nums)-3):
            for j in range(i + 1, len(nums)-2):
                p = j + 1
                q = len(nums) -1
                while p != q:
                    summer = nums[i] + nums[j] + nums[p] + nums[q]
                    if summer == target:
                        listT = [nums[i],nums[j],nums[p],nums[q]]
                        if listT not in resultList:
                            resultList.append(listT)
                        p = p + 1
                    elif summer > target:
                        q = q - 1
                    else:
                        p = p + 1
        return resultList

结果:AC

你可能感兴趣的:([LeetCode By Python] 18. 4Sum)