美文网首页
[LeetCode By Python] 18. 4Sum

[LeetCode By Python] 18. 4Sum

作者: 乐乐可爱睡觉 | 来源:发表于2016-06-17 15:57 被阅读419次

    一、题目

    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

          本文链接:https://www.haomeiwen.com/subject/kcevdttx.html