# Leetcode——两数之和（twoSum）、三数之和（threeSum）——Python

## 一、两数之和

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#对应每个测试案例，输出两个数，小的先输出。
# ls = []
# if not isinstance(nums, list):
#     return ls
# for i, v in enumerate(nums):
#     for v1 in nums[i:]:
#         if (v + v1) == target:
#             ls.append([v,v1])
# if ls:
#     return ls[0]
# else:
#     return ls

keys={}
for i in xrange(len(nums)):
if target-nums[i] in keys:
return [keys[target-nums[i]],i]
if nums[i] not in keys:
keys[nums[i]]=i


## 二、三数之和

class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res =[]
lennums= len(nums)

for i in range(lennums):
left =i+1
right =lennums-1

if i>0 and nums[i-1]==nums[i]:
left+=1
continue

while left<right:
sumthree = nums[i]+nums[left]+nums[right]
if sumthree==0:
res_col = [nums[i],nums[left],nums[right]]
res.append(res_col)
left+=1
right-=1

while nums[left]==nums[left-1] and left<right:
left+=1
while nums[right]==nums[right+1] and left<right:
right-=1

if sumthree<0:
left+=1
if sumthree>0:
right-=1
return res

06-01 4363

06-09 1580

04-26 2835

03-31 33

08-22 53

03-01 4286

10-14 189

10-30 811

02-19 524

09-07 2848

03-07 366

10-30 1773

11-16 203

09-24 640

11-29 25

10-16 367

03-19 82万+

07-01 1140

08-28 3604

04-19 44

08-08 6873

10-05 125

04-18 68

10-03 20

06-14 280

02-11 185

03-07 311

02-25 396

08-31 1143

03-21 1098

06-27 164

04-10 59

02-15 134

05-27 2873

04-11 165

03-18 5420

06-02 1478

02-13 294

05-09 108

05-09 3458

09-01 24

04-08 1851

05-09 392

08-28 473

04-02 1431

09-27 1046

05-01 127

04-08 392

08-26 226

03-31 1万+

10-10 2180

03-01 72

11-08 171

06-05 451

06-02 139

03-23 39

01-05 27万+

05-31 1099

08-24 88

08-19 143

06-17 340

06-09 3086

07-31 178

10-30 280

04-30 53

07-07 2938

08-22 5371

04-18 106

11-29 346

07-13 2353

02-22 736

04-15 136

03-03 44

06-24 381

04-24 38

11-01 29

01-24 111

04-14 59万+

#### 在中国程序员是青春饭吗？

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客