Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # sort and then use two pointers. avoiding duplicates was the real hassle. difficult implementation
- class Solution:
- def threeSum(self, nums: List[int]) -> List[List[int]]:
- nums.sort()
- result = []
- nums = list(set(nums))
- for index, num in enumerate(nums):
- # not needed, it's optimisation over the current approach to save
- # some computation time
- if num > 0:
- break
- # avoid duplicates
- if index!=0 and nums[index] == nums[index-1]:
- continue
- target = -num
- start = index + 1
- end = len(nums) - 1
- while(start < end):
- if nums[start] + nums[end] < target:
- start = start + 1
- elif nums[start] + nums[end] > target:
- end = end - 1
- else:
- result.append([nums[index], nums[start], nums[end]])
- start = start + 1
- end = end - 1
- while(start < end and nums[start] == nums[start-1]):
- start = start + 1
- while(start < end and nums[end] == nums[end+1]):
- end = end - 1
- return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement