Leetcode P15 three sum @python Lang (LL)
Link: https://leetcode.com/problems/3sum/
Content:
Method 1 - Brute Force
Algorithm:
- nums sort
- return is a list, build an empty array - res = []
- traverse i from 0 to len(nums-2)
traverse j from i+1 to len(nums-1)
traverse k from j+1 to len(nums) - if nums[i] + num[j] + nums[k] == 0 and this result has not in res[], return
Code:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
length=len(nums)
res=[]
for i in range(length):
for j in range (i+1,length):
for k in range(j+1,length):
sum=nums[i]+nums[k]+nums[j]
if sum==0 and not [nums[i],nums[j],nums[k]] in res:
# to avoid duplicate triplets
res.append([nums[i],nums[j],nums[k]])
return res
Attention ** Time Limit Exceeded**
Method 2 - Two pointers
Algorithm:
- nums sort
- return is a list, build an empty array - res = []
- traverse i, for loop, turn this problem to 2 sum.
two pointers, left from i+1, right from len(nums-1) - limit condition: while left < right
s = nums[i] + nums[left] + nums[right]
if s>0, right–; if s<0, left++
if s==0, res.append, left++, right–, return res
Code:
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
for i in range(len(nums)-2):
if i == 0 or nums[i] > nums[i-1]: # first avoid duplicate
left = i+1
right = len(nums)-1
while left < right:
s = nums[i] + nums[left] + nums[right]
if s == 0:
res.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
if nums[left] == nums[left-1]: # these two if, second to avoid duplicate
left += 1
if nums[right] == nums[right+1]:
right -= 1
elif s > 0:
right -= 1
else:
left += 1
return res
Time complexity:
O(n2)
Something needs to be noticed:
There are two places to avoid the duplicate triplets for method 2