codility CountDistinctSlices

Question:codility Lesson15 CountDistinctSlices

My Answer:

def solution(M,A):
    front = 0
    back = 0

    lenA = len(A)
    res = 0
    exist = [-1] * (M + 1)


    for front in range(lenA):
        if exist[A[front]] == -1:
            exist[A[front]] = front
        else:
            posback = exist[A[front]] + 1
            res += (posback - back) * (front - back + front - posback + 1)/2
            if res >= 1000000000:
                return 1000000000

            for i in range(back,posback):
                exist[A[i]] = -1

            exist[A[front]] = front

            back = posback

    res += (front - back + 1) * (front - back + 2) / 2

    return min(res,1000000000)

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