首页 > 试题广场 >

查找数组众数

[编程题]查找数组众数
  • 热度指数:5393 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个数组A[n], 定义数组的众数 ( Majority Element) 为数组中出现次数超过 n/2 次的元素, 假设数组A[n]非空且一定存在众数, 请设计算法找到该众数并输出.


输入描述:
一个非空且一定存在众数的整数数组,如: [1,2,2]


输出描述:
输出打印该众数,如: 2
示例1

输入

[1,2,2]

输出

2
示例2

输入

[3,1,-2,3,1,3,3]

输出

3
while True:
    try:
        s1 = input()
        s2 = list(set(s1))
        times = []
        for item in s2:
            times.append(s1.count(item))
        index = 0
        while index < len(s2):
            if times[index] > 0.5*len(s1):
                print(int(s2[index]))
            index += 1
    except:
        break
不明白为什么print不出结果呀?
发表于 2022-09-27 15:55:38 回复(0)
lst = input().replace("[","").replace("]","").replace(","," ").split()
#print(len(lst))
#print(int(9/2))#向下取整
l = []
for i in lst:
    if lst.count(i) > int(len(lst)/2):
        l.append(i)
ll = list(set(l))
print(''.join(ll))
暴力做法
发表于 2022-05-11 15:03:01 回复(0)