codility MinAbsSumOfTwo

Question:codility Lesson 15 MinAbsSumOfTwo

My Answer:

def solution(A):
    lenA = len(A)

    A.sort()

    if A[0] >= 0:
        return A[0] + A[0]

    if A[-1] <= 0:
        return abs(A[-1] + A[-1])

    front = lenA - 1
    back = 0

    minabs = A[-1] + A[-1]

    while back <= front:
        temp = abs(A[back] + A[front])

        if temp < minabs:
            minabs = temp

        if abs(A[back + 1] + A[front]) <= temp:
            back += 1
        elif abs(A[back] + A[front - 1]) <= temp:
            front -= 1
        else:
            back += 1
            front -= 1

    return minabs

你可能感兴趣的:(python,codility)