python 字典常用的

谁都会走 提交于 2020-02-20 07:22:54

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
(1)写法1

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        dic = collections.Counter(nums)
        for key,value in dic.items():
            if value > len(nums) / 2:
                return key

(2)写法2

class Solution(object):
    def majorityElement(self, nums):
        dic={}
        for num in nums:
            if num not in dic:
                dic[num]=1
            else:
                dic[num]=dic[num]+1
                if dic[num]>(len(nums)//2):
                    return num
        return nums[0]

统计某一个数字出现的次数时

dic[num]=dic.get(num,0)+1
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!