two_sum问题

def two_sum(li, target):
    for i in range(len(li)):
        for j in range(i+1, len(li)):
            if li[i] + li[j] == target:
                return i, j


def bin_search(li, val, low, high):
    while low <= high:  # 候选区有值
        mid = (low + high) // 2
        if li[mid] == val:
            return mid
        elif li[mid] > val:
            high = mid - 1
        else:   # li[mid] < val
            low = mid + 1
    return -1

def two_sum_2(li, target):
    for i in range(len(li)):
        a = li[i]
        b = target - a
        j = bin_search(li, b, i+1, len(li)-1)
        if j > 0:
            return i, j


def two_sum_4(li, target):
    d = {}
    for i, num in enumerate(li):
        a = li[i]
        b = target - a
        if b in d:
            return d[b], i
        else:
            d[a] = i





# [1,2,3,4]

 

posted @ 2018-12-24 20:59  小学弟-  阅读(116)  评论(0编辑  收藏  举报