求2数之和

# 暴力算法
def func1(li: list, target: int):
for i in range(len(li)):
for j in range(i + 1, len(li)):
if li[i] + li[j] == target:
return i, j
return -1, -1


# 字典转换
def func2(li: list, target: int):
temp = {}
for i in range(len(li)):
if temp.get(target - li[i], -1) > 0:
return temp.get(target - li[i]), i
temp[li[i]] = i
return temp.get(target - li[i], -1), -1


# 二分查找, 需要list已有序
def func3(li: list, target: int):
# li.sort()
for i in range(len(li)):
temp = target - li[i]
low = i+1
high = len(li) - 1
while low <= high:
mid = (low + high) // 2
if li[mid] == temp:
return i, mid
elif li[mid] < temp:
low = mid + 1
else:
high = mid - 1
return -1, -1


# 双指针, 需要list已有序
def func4(li: list, target: int):
# li.sort()
low = 0
high = len(li) - 1
while low <= high:
if li[low] + li[high] == target:
return low, high
elif li[low] + li[high] < target:
low += 1
else:
high -= 1
return -1, -1


if __name__ == '__main__':
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 17
print(func1(li, target))
print(func2(li, target))
print(func3(li, target))
print(func4(li, target))
posted @ 2022-05-14 10:34  狒狒桑  阅读(23)  评论(0编辑  收藏  举报