Given an array nums of n integers, are there elements a, b, c in nums 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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
1.三层循环暴力求解:
def threeSum(self, nums):
length = len(nums)
resultList = []
for i in range(0,length):
for j in range(i+1,length):
for k in range(j+1,length):
tSum = nums[i] + nums[j] + nums[k]
if tSum == 0:
result = []
result.append(nums[i])
result.append(nums[j])
result.append(nums[k])
result.sort()
if result not in resultList:
resultList.append(result)
return resultList
2.原数组排序,然后用两个指针夹逼
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
for i in xrange(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, len(nums)-1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
l +=1
elif s > 0:
r -= 1
else:
res.append((nums[i], nums[l], nums[r]))
while l < r and nums[l] == nums[l+1]:
l += 1
while l < r and nums[r] == nums[r-1]:
r -= 1
l += 1; r -= 1
return res
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
res = 0
diff = 2**32 - 1
nums.sort()
lens=len(nums)
for i in range(lens-2):
left=i+1
right=lens-1
while left<right:
temp_sum=nums[i]+nums[left]+nums[right]
temp_diff = abs(temp_sum-target)
if temp_diff<diff:
res=temp_sum
diff=temp_diff
if temp_sum<target:
left+=1
elif temp_sum>target:
right-=1
else:
return temp_sum
return res