mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 21:10:58 +08:00
modified 15. Add a new version with the same idea.
This commit is contained in:
@ -243,7 +243,34 @@ class Solution:
|
|||||||
right -= 1
|
right -= 1
|
||||||
return ans
|
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:
|
||||||
|
|
||||||
```Go
|
```Go
|
||||||
func threeSum(nums []int)[][]int{
|
func threeSum(nums []int)[][]int{
|
||||||
sort.Ints(nums)
|
sort.Ints(nums)
|
||||||
|
Reference in New Issue
Block a user