lc18:4Sum

187 阅读1分钟
  1. 4Sum Medium

1413

272

Add to List

Share 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] ]

思路:双指针,先定a,b两个数,nTarget=target-a-b 后面c=nums[b+1],d=nums[len(nums)-1], 如果c+d==nTarget,添加进set 如果c+d>nTArget,d往前进一位 如果c+d<nTArget,c往后进一位 注意去重,我这边为set加元组去重

代码:python3

class Solution:
    def fourSum(self, nums, target) :
      nums=sorted(nums)
      s=set()
      for x in range(0,len(nums)):
        a=nums[x]
        for y in range(x+1,len(nums)):
          b=nums[y]
          target1=target-a-b
          i=y+1
          j=len(nums)-1
          while(i<j):
            if nums[i]+nums[j]==target1:
              s.add((nums[x],nums[y],nums[i],nums[j]))
              i=i+1
              j=j-1                  
            elif nums[i]+nums[j]<target1:
              i=i+1
            else:
              j=j-1
      return list(s)
if __name__ == '__main__':
    print(Solution().fourSum([-3,-2,-1,0,0,1,2,3],0))