## leetcode01两数之和

2018年8月16日 发表评论 阅读评论

### 一、题目

```给定 nums = [2, 7, 11, 15], target = 9

### 二、代码实现

#### 1、找出对应值

```nums = [2, 7, 11, 15]
target = 9
l = []
for x in nums:
for y in nums:
if (x + y) == target:
#print x,y
l.append(x)
l.append(y)
print list(set(l))```

#### 2、打印下标

```nums = [3,2,4]
target = 6
n = range(len(nums))
l = []
for x in n:
for y in n:
# [3,3] 6
#if nums[x] != nums[y]:
if x != y:
if nums[x] + nums[y] == target:
print x,y
l.append(x)
l.append(y)
print list(set(l))```

```nums = [3,2,4]
target = 6```

#### 3、暴力推导

```from itertools import combinations
nums = [2, 7, 11, 15]
l = [c for c in  combinations(nums, 2)]
n = [ x  for x in l if sum(x)==9]
m = [ x for x in range(len(nums)) if nums[x]==n[0][0] or nums[x]==n[0][1] ]
print m```

#### 4、最终实现

```#!/usr/bin/env python
# coding=utf8
# ===============================================================================
#
#   Filename      ：01sum.py
#   Author        ：yangbk <itybku@139.com>
#   Create Time   ：2018-08-16 14:33
#   Description   ：
# ===============================================================================
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i in range(len(nums)):
#y = target - nums[x]
x = nums[i]
if target-x in d:
return [d[target-x],i]
d[x] = i```

You can donate through PayPal.
My paypal id: itybku@139.com
Paypal page: https://www.paypal.me/361way

1. 本文目前尚无任何评论.
1. 本文目前尚无任何 trackbacks 和 pingbacks.