LeetCode 两数之和、三数之和

1. 两数之和

class Solution:
def twoSum(self, nums, target):
d = {}
for i in range(len(nums)):
x = target - nums[i]
if x in d:
return [d[x],i]
else:
d[nums[i]] = i

1. 三数之和

[
[-1, 0, 1],
[-1, -1, 2]
]


def threeSum1(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""

a = []

n = len(nums)

for  i in range(n):
for j in range(n):
for k in range(n):
if  i != j  and j!= k  and i!=k  and nums[i] + nums[k] + nums[j] == 0:
if sorted([nums[i], nums[j], nums[k]]) not in a:
a.append( sorted([nums[i], nums[j], nums[k]]))
return a

# 超时  O（n3 * n㏒n）


a+b = -c，两个lops 加list存储 ，继续超时

    def threeSum2(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
## nums = [-1,0,1,2,-1,-4]
## sort nums = [-4, -1, -1, 0, 1, 2]
## d = set([0, 1, 2, -4, -1])
# 思路优化：   求 a+b = -c 即可
n = len(nums)

nums.sort()

if n < 3 :
return []
d = {}
res= []
for di,dv in enumerate(nums):
d[dv] = di
for i1,v1 in enumerate(nums):
for i2,v2 in enumerate(nums):
if -(v1 +v2)  in d   and i1 != i2 and  i1!= d[-(v1 +v2)] and i2 !=d[-(v1 +v2)]  :
if sorted([v1,v2,-(v1+v2)]) not  in res:
res.append(sorted([v1,v2,-(v1+v2)]))

return res

# 超时  O（n2 * n㏒n）




def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""

# 思路优化：   求 a+b = -c 即可
nums.sort()
res = set()
for i,v in enumerate(nums[:-2]):
if i>=1 and v == nums[i:-1]:
continue
d = {}
for x in nums[i+1:]:
if x not in d:
d[-v-x] =1
else: