最容易想到的
import numpy as np
a=np.random.randint(100,size=10)
n=len(a)
c=a[n-2]+a[n-1]
for i in range(n):
for j in range(i,n):
if a[i]+a[j]==c:
print(i,j)
import numpy as np
a=np.random.randint(100,size=10)
n=len(a)
c=a[n-2]+a[n-1]
d={}
temp=[]
for i in range(n):
if a[i] in d:
print(i,d[a[i]])
temp.append([i,d[a[i]]])
else:
d[c-a[i]]=i
print(a[temp[0][0]],'+',a[temp[0][1]],'=',c)
#
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import time
import numpy as np
'''
class Solution:
def twoSum(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#用len()方法取得nums列表的长度
n = len(nums)
#x取值从0一直到n(不包括n)
for x in range(n):
#y取值从x+1一直到n(不包括n)
#用x+1是减少不必要的循环,y的取值肯定是比x大
for y in range(x+1,n):
#假如 target-nums[x]的某个值存在于nums中
if nums[y] == target - nums[x]:
#返回x和y
return x,y
break
else:
continue
'''
class Solution:
def twoSum(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#用len()方法取得nums列表长度
n = len(nums)
#创建一个空字典
d = {}
for x in range(n):
a = target - nums[x]
#字典d中存在nums[x]时
if nums[x] in d:
return d[nums[x]],x
#否则往字典增加键/值对
else:
d[a] = x
# print(d)
#边往字典增加键/值对,边与nums[x]进行对比
a=np.random.randint(10000000,size=100000)
n=len(a)
c=a[n-2]+a[n-1]
cc=Solution()
t1=time.time()
cc1=cc.twoSum(list(a),c)
print((t1-time.time())*1000,'毫秒')
print(cc1)