3sum solution python

Solutions on MaxInterview for 3sum solution python by the best coders in the world

showing results for - "3sum solution python"
Mariana
01 Jan 2018
1class Solution(object):
2   def threeSum(self, nums):
3      nums.sort()
4      result = []
5      for i in range(len(nums)-2):
6         if i> 0 and nums[i] == nums[i-1]:
7            continue
8         l = i+1
9         r = len(nums)-1
10         while(l<r):
11            sum = nums[i] + nums[l] + nums[r]
12            if sum<0:
13               l+=1
14            elif sum >0:
15               r-=1
16            else:
17               result.append([nums[i],nums[l],nums[r]])
18               while l<len(nums)-1 and nums[l] == nums[l + 1] : l += 1
19               while r>0 and nums[r] == nums[r - 1]: r -= 1
20               l+=1
21               r-=1
22      return result
23ob1 = Solution()
24print(ob1.threeSum([-1,0,1,2,-1,-4]))