欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode-169 多数元素 Python

程序员文章站 2024-03-22 14:04:58
...

方法一:

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        dic = {}
        for i in nums:
            dic[i] = dic.get(i, 0) + 1
            if dic[i] >= len(nums)/2:
                return i

方法二:

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        if not nums:
            return None
        dic = {}
        for i in nums:
            if i not in dic:
                dic[i] = 1
            else:
                dic[i] += 1 
        max = 0
        for key.val in dic.items():
            if val > max:
                max = val
                pos = key
        if max > int(len(nums)/2):
            return pos

方法三:

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        if not nums:
            return None
        dic = {}
        for i in nums:
            if i not in dic:
                dic[i] = 1
            else:
                dic[i] += 1 
        max = 0
        for key, val in dic.items():
            if val > max:
                max = val
                pos = key
        if max > int(len(nums)/2):
            return pos

方法四:投票算法

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        m = cm = 0
        for num in nums:
            if m == num:
                cm += 1
            elif cm == 0:
                m = num
                cm = 1
            else:
                cm -= 1
        return m

方法五:排序

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        return nums[len(nums)//2]

上一篇: spark常见错误

下一篇: Reverse Integer