← switch

169. Majority Element

easy

Array · Hash Table · Divide and Conquer · Sorting · Counting · Boyer–Moore Majority Vote Algorithm

read the problem on leetcode →

first solved 13 Aug 2024 · 2 accepted submissions

python
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        major=None 
        count =0
        for num in nums:
            if count==0:
                major=num

            if num==major:
                count+=1
            else:
                count-=1
        return major
        


        
        
python
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        cand=nums[0]
        candiscore=0
        for i in nums:
            if candiscore==0:
                cand=i
            if i==cand:
                candiscore+=1

            else:
                candiscore-=1
               
                
        return cand