08 找出整型数组中占比超过一半的数

71 阅读1分钟

找出整型数组中占比超过一半的数

题目描述

小R从班级中抽取了一些同学,每位同学都会给出一个数字。已知在这些数字中,某个数字的出现次数超过了数字总数的一半。现在需要你帮助小R找到这个数字。

测试样例

样例1:

输入:array = [1, 3, 8, 2, 3, 1, 3, 3, 3] 输出:3

样例2:

输入:array = [5, 5, 5, 1, 2, 5, 5] 输出:5

样例3:

输入:array = [9, 9, 9, 9, 8, 9, 8, 8] 输出:9

💡Idea

  • dict字典存储每个数字出现的个数作为value,然后按照次数排序,输出Key

    代码如下:

    def solution(array):
        # Edit your code here
        dt = {}
        for i in array:
            if i in dt:
                dt[i] += 1
            else:
                dt[i] = 1
        st_dt = sorted(dt.items(), key=lambda x: -x[1])
        return st_dt[0][0]
    

    数据结构dict or hashmap

    时间复杂度O(n+nlog(n))O(nlog(n))O(n + nlog(n)) \approx O(nlog(n))

    • O(n)O(n)for循环
    • O(nlog(n))O(nlog(n))sort排序

    空间复杂度O(n)O(n) CPP中的hashmap

💡💡Other

  • 通过对pythonCounter使用

    用法如下:

    def solution(array):
        # Edit your code here
        from collections import Counter # 导入‘Counter’
        c = Counter(array) # The type of C is <class 'collections.Counter'>.
        return next(k for k, v in c.items() if v * 2 > len(array))
    

    Counter的实现是模拟for循环计数,时间O(n)O(n)

    next(k for k, v in c.items() if v * 2 > len(array))O(n)O(n),next返回迭代元素

    其实这个用法和第一个一样,只是让第一解法不用Sort排序

    数据结构dict or hashmap Counter 内部依旧是 dict or hashmap

    时间复杂度O(n+n)O(n)O(n + n) \approx O(n)

    空间复杂度O(n)O(n) CPP中的hashmap

Ending ...