Iam_Sandeep

Moores voting algorithm . number which is repeating more than half the size of array

Sep 16th, 2021 (edited)
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.63 KB | None | 0 0
  1. https://leetcode.com/problems/majority-element/submissions/
  2. class Solution:
  3.     def majorityElement(self, nums: List[int]) -> int:
  4.         major=nums[0]
  5.         count=1
  6.         n=len(nums)
  7.         for i in range(1,n):
  8.             if nums[i]==major:
  9.                 count+=1
  10.             else:
  11.                 if count>1:
  12.                     count=count-1
  13.                 else:
  14.                     count=1
  15.                     major=nums[i]
  16.         check=0
  17.         for i in range(n):
  18.             if nums[i]==major:
  19.                 check+=1
  20.         if check>n//2:
  21.             return major
  22.            
  23.            
  24.        
Add Comment
Please, Sign In to add comment