Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Here's my pythonic approach to the LeetCode 3Sum problem. It passes and actually beats 93% in time! However, the code is unwieldy, and the approach seems much overly complicated. I am looking to clean up the twoSum
function, and overall approach, but I'm not sure how.
def threeSum(self, nums: List[int]) -> List[List[int]]: def twoSum(i,target): ans = [] for j in range(i+1,len(nums)): #avoid dupes if j > i+1 and nums[j] == nums[j-1]: continue if nums[j] > target//2: break # when target is even, two dupes may add to make it if nums[j] == target/2 and j+1 < len(nums): if nums[j+1] == target // 2: ans.append([nums[i],nums[j],nums[j+1]]) break #traditional two sum variation elif -(-target + nums[j]) in values and -(-target + nums[j]) != nums[j]: ans.append([nums[i],nums[j],-(-target + nums[j])]) return ans values = set(nums) nums.sort() answer = [] for i,num in enumerate(nums): if i > 0 and nums[i-1] == nums[i]: continue values.remove(num) answer.extend(twoSum(i,-num)) return answer
Even if you aren't able to follow my code, I would really appreciate general pythonic tips.