找出主元素

shaoSaxon / 2024-02-29 / 原文

题目

给定一个整型数组,找出数组中出现最多的数

题解

创建一个空字典,
在遍历数组时为字典赋值,
数组遍历完成后,
寻找值最大的那个键,
然后,输出这个键

    def majority_number(self, nums: List[int]) -> int:
        # write your code here
        count_dict={}
        for num in nums:
            if num in count_dict:
                count_dict[num]+=1 #遇到字典中重复的则将值+1
            else:
                count_dict[num]=1#遇到字典中没有的值则将值设定为1
        #通过遍历字典查找最大值的那个键,最后输出
        max_count=0
        most_num=None
        for key,value in count_dict.items():
            if value>max_count:
                max_count=value
                most_num=key
        return most_num