[Bit operation-simple] Sword refers to Offer 39. Numbers that appear more than half the number of times in the array (three solutions: voting + dictionary + median)

[Title] The
number of occurrences of a number in the array exceeds half of the length of the array. Please find out this number.
You can assume that the array is non-empty, and there will always be a majority of elements in a given array.
[Example 1]
Input: [1, 2, 3, 2, 2, 2, 5, 4, 2]
Output: 2
[Limits]
1 <= array length <= 50000
[Code]
[Python]
Insert picture description here

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

[Method 2]
Insert picture description here

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        num=nums[0]
        cnt=1
        for i in range(1,len(nums)):
            if nums[i]==num:
                cnt+=1
            else:
                cnt-=1
                if cnt==0:
                    cnt=1
                    num=nums[i]
        return num

[Method 3]
Insert picture description here

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        cnt=dict(Counter(nums))
        cnt=sorted(cnt.items(),key=lambda x:x[1])
        return cnt[-1][0]

Guess you like

Origin blog.csdn.net/kz_java/article/details/115100268