找出整型数组中占比超过一半的数
题目描述:
小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]数据结构:
dictorhashmap时间复杂度:
- 为
for循环 - 为
sort排序
空间复杂度:
CPP中的hashmap - 为
💡💡Other
-
通过对
python的Counter使用用法如下:
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循环计数,时间next(k for k, v in c.items() if v * 2 > len(array))为,next返回迭代元素其实这个用法和第一个一样,只是让第一解法不用Sort排序数据结构:
dictorhashmapCounter 内部依旧是dict or hashmap时间复杂度:
空间复杂度:
CPP中的hashmap
Ending ...