思想:
1.申请一个数组保存原数组的下标变化,然后将原数组排序,之后返回变化的下标(排序过程中,容易超时);
2,(参考别人解法):使用词典;
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
dict_num = dict()
for i in num:
dict_num[i] = 1
for i in range(len(num) - 1):
if not target - num[i] in dict_num:
continue
for j in range(i + 1, len(num)):
if num[i] + num[j] == target:
return i + 1, j + 1
自己实现的:
lass Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
index = range(len(num))
for i in range(len(num)):
for j in range(len(num)-1):
if num[j] > num[j+1]:
num[j],num[j+1] = num[j+1],num[j]
index[j],index[j+1] = index[j+1],index[j]
i=0
m=len(num)-1
index1 = 0
index2 = 0
while i target:
m = m -1
elif num[i]+num[m] < target:
i = i + 1
else:
index1 = min([index[i],index[m]])
index2 = max([index[i],index[m]])
break
return index1,index2