modified 15. Add a new version with the same idea.

This commit is contained in:
Camille0512
2022-02-25 00:57:43 +08:00
parent e54ba10fa1
commit 5b78393ac4

View File

@ -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)