首页 > 试题广场 >

微信红包

[编程题]微信红包
  • 热度指数:34672 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。

给定一个红包的金额数组 gifts 及它的大小 n ,请返回所求红包的金额。

若没有金额超过总数的一半,返回0。

数据范围: ,红包金额满足
示例1

输入

[1,2,3,2,2],5

输出

2
示例2

输入

[1,1,2,2,3,3],6

输出

0
class Gift:
    def getValue(self, gifts, n):
        global key
        result = {}
        for i in gifts:
            if i in result:
                result[i] += 1
            else:
                result[i] = 1
        MAX = (max(result.values()))
        if MAX > n / 2:
            for key in result.keys():
                if result[key] == MAX:
                    print(key)

        else:
            print(0)
            
            
            
            
       

发表于 2022-01-13 14:01:20 回复(1)

class Gift:
    def getValue(self, gifts, n): 
        from collections import Counter
        maxNum_sample = Counter(gifts).most_common(1)
        m=maxNum_sample[0] 
        if m[1]>n/2: 
            return m[0] 
        else: 
            return 0


发表于 2021-03-16 12:33:53 回复(0)
class Gift:
    def getValue(self, gifts, n):
        unique=set(gifts)#用set集合去掉重复的红包金额
        for i in unique:
            if gifts.count(i)>n//2:#出现次数大于总数一半,返回红包金额
                return i
        return 0#没有金额超过总数的一半,返回0

发表于 2018-07-12 15:52:27 回复(0)

python两行代码的解法如下,当然也可以压缩成一行,我就不***了。

from collections import Counter

class Gift:
    def getValue(self, gifts, n):
        a = Counter(gifts).most_common(1)[0]
        return a[0] if a[1] > n // 2 else 0
发表于 2017-09-12 14:44:55 回复(4)
class Gift:
    def getValue(self, gifts, n):
        # write code here
        nums = {}
        for i in range(n):
            money = gifts[i]
            if nums.get(money):
                nums[money] += 1
                if nums.get(money) > n/2:
                    return money
            else:
                nums[money] = 1
        return 0 
发表于 2017-03-24 10:52:24 回复(0)

问题信息

难度:
5条回答 41208浏览

热门推荐

通过挑战的用户

查看代码