luoheng
8/31/2019 - 6:24 AM

序列中出现次数超过n/3的元素

# 找到次数超过n/3的元素

def find_over_1_3(A):
    length = len(A)
    num = [0, 0]
    count = [0, 0]
    for i in A:
        if i in num:
            count[num.index(i)] += 1
        else:
            if 0 in count:
                num[count.index(0)] = i
                count[count.index(0)] = 1
            else:
                count[0] -= 1
                count[1] -= 1
    L = []
    if count[0] != 0 and A.count(num[0]) > length / 3:
        L.append(num[0])
    if count[1] != 0 and A.count(num[1]) > length / 3:
        L.append(num[1])
    return L

def main():
    A = [3, 2, 1, 3, 4, 3, 1, 3, 1, 5, 1, 2, 3, 1]
    print(find_over_1_3(A))

if __name__ == "__main__":
    main()