18. 4Sum **
来源:互联网 发布:淘宝店铺的托管靠谱 编辑:程序博客网 时间:2024/06/13 10:34
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]]My code:
class Solution(object): def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ n = len(nums) result = [] nums.sort() for i in range(n-3): if nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target: break if i ==0 or (i>0 and nums[i]!=nums[i-1]): for j in range(i+1,n-2): if nums[i]+nums[j]+nums[j+1]+nums[j+2]>target: break low = j+1 high = n-1 while low<high: if nums[low]+nums[high]==target-nums[i]-nums[j] and [nums[i],nums[j],nums[low],nums[high]] not in result: result.append([nums[i],nums[j],nums[low],nums[high]]) while (low < high and nums[low] == nums[low+1]): low+=1 while (low < high and nums[high] == nums[high-1]): high-=1 low +=1 high-=1 elif nums[low]+nums[high]>target-nums[i]-nums[j]: while (low < high and nums[high] == nums[high-1]): high-=1 high -=1 else: while (low < high and nums[low] == nums[low+1]): low+=1 low +=1 return result
0 0
- 15. 3Sum 和 18. 4Sum
- LeetCode --- 18. 4Sum
- [Leetcode] 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum LeetCode
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 插入排序
- Java锁--Lock实现原理(底层实现)
- Java(线程的概念)(线程和进程的比较)(多线程的优点)
- Android Studio编译优化
- 【OpenCV入门教程之十四】OpenCV霍夫变换:霍夫线变换,霍夫圆变换合辑
- 18. 4Sum **
- 随机生成文件名
- activity四种启动方式
- ffmgeg使用手册
- 子网掩码讲解
- Java jdbc批量多线程读取CVS文件入库
- LeetCode 201. Bitwise AND of Numbers Range
- bat命令运行java程序
- 背包九讲之完全背包问题