3Sum LeetCode solution in Python
1class Solution(object):2def threeSum(self, nums):3ans = []4nums.sort()56for i in range(len(nums)):7if nums[i] > 0:8break # after sorting, if the min > 0, we couldn't find such three values9if (10i > 0 and nums[i] == nums[i - 1]11): # ensure that nums[i] is not duplicated12continue13l, r = i + 1, len(nums) - 114while l < r:15if nums[l] + nums[r] > -nums[i]:16r -= 117elif nums[l] + nums[r] < -nums[i]:18l += 119else:20ans.append([nums[i], nums[l], nums[r]])21# update l to get a different sum22l += 123while nums[l] == nums[l - 1] and l < r:24l += 125return ans