Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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]
]
My code:
import numpy as np
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result=[]
index=np.argsort(nums)
for i in range(len(nums)-2):
if i>=1:
if nums[index[i]]==nums[index[i-1]]:
continue
require=-nums[index[i]]
#print(-require)
lstart=i+1
rstart=len(nums)-1
while lstart<rstart:
number1=nums[index[lstart]]
number2=nums[index[rstart]]
#print('lstart %d value %d'%(lstart,number1))
if number1+number2==require:
result.append([-require,number1,number2])
while nums[index[lstart+1]]==nums[index[lstart]] and lstart+1<rstart:
lstart+=1
while nums[index[rstart-1]]==nums[index[rstart]] and rstart-1>lstart:
rstart-=1
lstart+=1
rstart-=1
elif number1+number2>require:
rstart-=1
else:
lstart+=1
return result
#This is a o(n^2) operation, but python version can't pass the leetcode testing. I can say there will be no better algorithms better than this.So do not worry about time problem.
Solution:
https://leetcode.com/problems/3sum/