Example #1
0
def two_sum_fast(lst):
    """
      Count the number of pair of numbers add up to zero. first sort the list,
    then use binary_search the get the other number which could add up to zero,
    if in the list, then increase the counter.
    >>> lst = [-1, 1, -2, 3, 5, -5, 0, 4]
    >>> two_sum_fast(lst)
    2
    """
    lst.sort()
    cnt = 0
    for i in range(len(lst)):
        if binary_search(-lst[i], lst) > i:
            cnt += 1
    return cnt
Example #2
0
def three_sum_fast(lst):
    """
      Count how many three numbers add up to zero. first sort the list,
    then using two for-loop and binary search algorithm get the opposite number.
    >>> lst = [-1, 2, 1, 3, 0, 4, -4, 5, 9, -5]
    >>> three_sum_fast(lst)
    8
    """
    lst.sort()
    cnt = 0
    for i in range(len(lst)):
        for j in range(i + 1, len(lst)):
            if binary_search(-lst[i] - lst[j], lst) > j:
                cnt += 1
    return cnt