zoukankan      html  css  js  c++  java
  • 18. 4Sum

    Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

    Note:

    The solution set must not contain duplicate quadruplets.

    Example:

    Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

    A solution set is:
    [
    [-1, 0, 0, 1],
    [-2, -1, 1, 2],
    [-2, 0, 0, 2]
    ]

    class Solution:
        def fourSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[List[int]]
            """
            nums.sort()
            # print(nums)
            res = set()
            for i in range(len(nums)-3):
                # if i>0 and nums[i]==nums[i-1]:
                #     continue
                if 4*nums[i]>target:
                    break
                for j in range(i+1,len(nums)-2):
                    # if j>i+1 and nums[j]==nums[j-1]:
                    #     continue
                    if 3*nums[j]>target - nums[i]:
                        break
                    left,right = j+1,len(nums)-1
                    # print('i:',i,'j:',j,'left:',left,'right:',right)
                    while left<right:
                        ans = nums[i]+nums[j]+nums[left]+nums[right]
                        if ans==target:
                            res.add((nums[i],nums[j],nums[left],nums[right]))
                            left += 1
                            right -= 1
                            continue
                        if ans>target:
                            right -= 1
                            continue
                        if ans<target:
                            left += 1
            return [list(i) for i in res]
    
  • 相关阅读:
    网络之传输层
    局域网的物理组成
    网络基础
    RAID磁盘阵列
    mount挂载和交换分区swap
    Linux文件系统
    sed命令基础2
    sed命令基础
    LVM基础
    磁盘配额基础
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9783644.html
Copyright © 2011-2022 走看看