题目解析|找出整型数组中占比超过一半的数

37 阅读1分钟

思路很直接,统计数组中每一个值的频率,创建一个哈希表用空间换时间,优化查询效率

def solution(array):
    # Edit your code here
    n=len(array)
    hash_dict={}
    for value in array:
        hash_dict[value]=hash_dict.get(value,0)+1
        if hash_dict[value]/n>0.5:
            return value
    return 0


if __name__ == "__main__":
    # Add your test cases here

    print(solution([1, 3, 8, 2, 3, 1, 3, 3, 3]) == 3)