题解 | 数组中出现次数超过一半的数字
数组中出现次数超过一半的数字
https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param numbers int整型一维数组 # @return int整型 # class Solution: def MoreThanHalfNum_Solution(self , numbers: List[int]) -> int: # write code here data = set(numbers) length = len(numbers) for i in data: count = 0 for j in range(length): if i == numbers[j]: count = count + 1 if count > length/2: return i
这个用python做比较简单,因为list转换为set集合可以去重,这样遍历的时候,只要比较set中的各个元素在list中出现的频率就可以实现对应的功能了。
c的代码我还没想,但是我想应该比python代码要难多了。