18. 4Sum (python)
来源:互联网 发布:刷帮豆软件 编辑:程序博客网 时间:2024/06/04 19:12
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]
]
题意:在数组S中找到四个元素相加和为0,当然要去重
思路:采用快速排序法只排一次,每次取一个数x,问题转化为target-x的3sum问题
时间复杂度为O(n^3)
第一个:每次取一个数,只将该元素后续的列表中查找target-x的3sum和;
第二个:每次取一个数,需要判断是否和前一个数重复(循环起始数除外),只有不重复才进行3sum计算,重复则continue
3sum计算同理,就能避免重复
第三个:在进行2sum计算,若2sum的和等于target后,需要将左右指针移位,过滤后续重复元素,直到元素不重复再计算2sum之和
Runtime: 892 ms
class Solution(object): def fourSum(self, nums, target): if len(nums)<=3: return [] nums=sorted(nums) four=[] for i in range(0,len(nums)-3): if nums[i]==nums[i-1] and i!=0: continue for j in range(i+1,len(nums)-2): if nums[j]==nums[j-1] and j!=i+1: continue t=target-nums[i]-nums[j] l,r=j+1,len(nums)-1 while l<r: s=nums[r]+nums[l] if s==t: four.append([nums[i],nums[j],nums[l],nums[r]]) l+=1 r-=1 while l<r and nums[l]==nums[l-1]: l+=1 while l<r and nums[r]==nums[r+1]: r-=1 elif s<t: l+=1 else: r-=1 return four
0 0
- 18. 4Sum (python)
- 18. 4Sum Leetcode Python
- 【Leetcode】【python】4Sum
- leetcode 018 4sum (Python)
- 18. 4Sum leetcode Python 2016 new Season
- python写算法题:leetcode: 18. 4Sum
- python sum
- leetcode 131: 4sum by python
- 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
- 【多媒体之声音总结】
- 16. 3Sum Closest (python)
- HDU 1503Advanced Fruits 递推
- 分类(1):决策树与模型评估
- uC/OS-III Note
- 18. 4Sum (python)
- php中魔术变量解析
- Astar A*算法 最短路径算法
- word-wrap、white-space和word break的区别
- iOS开发小技巧汇总
- Mybatis简易介绍
- 整合dtk + hpssacli2.4
- python学习[2]_Python中面向对象编程1
- Struts2使用客户端校验