其他分享
首页 > 其他分享> > leetcode 18-> 4Sum

leetcode 18-> 4Sum

作者:互联网

 

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        
        l = len(nums)
        nums.sort()
        if l < 4:
            return []
        res = []
        for i in range(l-3):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            elif nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target:
                break
            elif nums[i] + nums[l-3] + nums[l-2] + nums[l-1] < target:
                continue
            for j in range(i+1, l-2):
                if j > i+1 and nums[j] == nums[j-1]:
                    continue
                elif nums[i] + nums[j] + nums[j+1] + nums[j+2] > target:
                    break
                elif nums[i] + nums[j] + nums[l-2] + nums[l-1] < target:
                    continue
                k = j+1
                p = l-1
                s = target - nums[i] - nums[j]
                while k < p:
                    if nums[k] + nums[p] > s:
                        p -= 1
                    elif nums[k] + nums[p] < s:
                        k += 1
                    else:
                        res.append([nums[i], nums[j], nums[k], nums[p]])
                        while k < p and nums[k] == nums[k+1]:
                            k += 1
                        while k < p and nums[p] == nums[p-1]:
                            p -= 1
                        k += 1
                        p -= 1
        return res

 

标签:4Sum,elif,target,nums,int,18,continue,res,leetcode
来源: https://www.cnblogs.com/sea-stream/p/10525045.html