diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index e191eabc..1d811b76 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -243,7 +243,34 @@ class Solution: right -= 1 return ans ``` +Python (v2): + +```python +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + if len(nums) < 3: return [] + nums, res = sorted(nums), [] + for i in range(len(nums) - 2): + cur, l, r = nums[i], i + 1, len(nums) - 1 + if res != [] and res[-1][0] == cur: continue # Drop duplicates for the first time. + + while l < r: + if cur + nums[l] + nums[r] == 0: + res.append([cur, nums[l], nums[r]]) + # Drop duplicates for the second time in interation of l & r. Only used when target situation occurs, because that is the reason for dropping duplicates. + while l < r - 1 and nums[l] == nums[l + 1]: + l += 1 + while r > l + 1 and nums[r] == nums[r - 1]: + r -= 1 + if cur + nums[l] + nums[r] > 0: + r -= 1 + else: + l += 1 + return res +``` + Go: + ```Go func threeSum(nums []int)[][]int{ sort.Ints(nums)