4sum
来源:互联网 发布:老男孩linux 编辑:程序博客网 时间:2024/06/05 20:04
# *- coding:utf-8 -* '''Given an array S of n integers, are there elements a, b, c, and d in S 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.For example, given array S = [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(object): def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ res=[] len_n=len(nums) if len_n < 4 : return res nums=sorted(nums) for i in range(0,len_n-3): if i>0 and nums[i]==nums[i-1]: continue if sum(nums[i:i+4]) > target : break if nums[i]+sum(nums[-3:])<target: continue for j in range(i+1,len_n-2): if j>i+1 and nums[j]==nums[j-1]: continue if nums[i]+sum(nums[j:j+3]) > target: break if nums[i]+nums[j]+sum(nums[-2:]) < target: continue left=j+1 right=len_n-1 while left<right: sum_r=nums[left]+nums[right]+nums[i]+nums[j] if sum_r < target: left+=1 elif sum_r > target: right-=1 else: res.append([nums[i],nums[j],nums[left],nums[right]]) while left<right and nums[left]==nums[left+1]: left+=1 left+=1 while left<right and nums[right]==nums[right-1]: right-=1 right-=1 return resmy_res=Solution()nums= [-1,0,-5,-2,-2,-4,0,1,-2]target=-9print my_res.fourSum(nums,target)
阅读全文
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 2Sum 3Sum 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- Unique Paths问题及解法
- POJ2387 Til the Cows Come Home [kuangbin] 最短路
- ElasticSearch与大数据的不解情缘
- HDU.1495 非常可乐 (BFS)
- ssh和ssm的区别,好处
- 4sum
- POJ2975--Nin(Nin博弈)
- Python2.*与Python3.*共存问题
- Python 2.7下下载并安装nltk (自然语言处理工具包)
- 汇编Writing to Files
- 高效的php过滤敏感词方法
- java 泛型详细解释
- poj 2559
- Python2.*与Python3.*共存问题