python 求众数 LeetCode N0.169

python 求众数 LeetCode N0.169python 求众数 LeetCode N0.169_第1张图片

这道题有很多解法官方leetcode上面是六种,由于说的太过于详细,我都不好意思,再补充什么了。所以我就写了一点,没看答案之前的写法,和我觉得,需要掌握的写法吧。他写的很多代码很精简,值得学习。(ps,纳闷的是,即使我用的O(n)的复杂度,排名也很靠后哈哈哈哈哈)

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #count = 0
        #candidate = None

        #for num in nums:
        #   if count == 0:
        #        candidate = num
        #    count += (1 if num == candidate else -1)

        #return candidate

        count = 0
        candidate = nums[0]
        for i in range(len(nums)):
            if nums[i] == candidate:
                count += 1
            else:
                count -= 1
            if count == 0:
                candidate =nums[i+1]
        return candidate
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        import math
        count = {}
        if len(nums) %2 == 1:
            n = len(nums)+1
        else :
            n = len(nums)
        for i in nums:
            count[i] = count.get(i,0) + 1
            
            if count[i] >= n/2:
                return i
        for i in nums:
            if count[i] >= n/2:
                return i
class Solution:
    def majorityElement(self, nums):
        counts = collections.Counter(nums)
        return max(counts.keys(), key=counts.get)

#作者:LeetCode
#链接:https://leetcode-cn.com/problems/majority-element/solution/qiu-zhong-shu-by-leetcode-2/
#来源:力扣(LeetCode)
#著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(python,求众数,LeetCode,169,python,LeetCode,面试)