一.问题描述
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
二.算法设计&优化
寻找三个数使其总和为0,暴力解法复杂度为O(N^3)。因此考虑通过排序(O(NlogN))来优化算法。我们知道对于有序的序列的TwoSum算法复杂度是O(N),而3Sum不过就是固定一个数的TwoSum。因此解法为一次固定数组中的一个数,求剩下数组的TwoSum使其和加上固定的数之和为零。显而易见,该算法时间复杂度为O(N^2)。
我最初在设计3Sum这个算法的时候只是排了序,然后固定一个数,再求TwoSum的时候只是简单地判定不存在的情况就跳过,代码如下:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = len(nums)
outputlist = []
nums.sort()
for i in range(n-1):
if i>0 and nums[i] == nums[i-1]:
continue
for j in range(n-1,i,-1):
if j<n-1 and nums[j] == nums[j+1]:
continue
jj = j-1
while jj>i:
if nums[i]+nums[jj]>nums[jj]:
break
elif nums[i]+nums[j]+nums[jj]==0:
outputlist.append([nums[i],nums[jj],nums[j]])
break
jj = jj-1
return outputlist
显然该算法复杂度是高于O(N^2)的。
我根据上上述算法优化后所写的时间复杂度为O(N^2)的算法如下:
#?原理很简单不想写了?(^人^) #
三.问题扩展
3Sum的问题可以通过固定一个数转化成TwoSum的问题,那么显然KSum的问题不断地转化最后变成TwoSum的问题。我们知道KSum的问题暴力解法的时间复杂度会达到O(N^k),而通过一步步退化成TwoSum,其时间复杂度可以降低到O(N^(k-1)),这个貌似是最好的界了。KSum算法可以通过递归来实现。附上我写的4Sum的代码:
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
len_nums = len(nums)
if len_nums < 4:
return []
re_list = []
# sort
nums.sort()
for i in range(len_nums):
# need the unique one
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, len_nums - 2):
# need the unique one
if j-1!= i and nums[j] == nums[j - 1]:
continue
target1 = target - nums[i] - nums[j]
m = j + 1
n = len_nums - 1
while m < n:
if nums[m] + nums[n] > target1:
n = n - 1
elif nums[m] + nums[n] < target1:
m = m + 1
else:
re_list.append([nums[i], nums[j], nums[m], nums[n]])
while m + 1 < len_nums and nums[m + 1] == nums[m]:
m = m + 1
while n - 1 > j + 1 and nums[n - 1] == nums[n]:
n = n - 1
m = m + 1
n = n - 1
return re_list