Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- SC - O(n)
- TC - O(n) - Booyer-Moore algo
- class Solution:
- def majorityElement(self, nums: List[int]) -> int:
- """
- Finds the majority element in the given list using the Boyer-Moore Voting Algorithm.
- A majority element is an element that appears more than ⌊n/2⌋ times in the list.
- Algorithm:
- 1. Initialize a candidate as None and count as 0.
- 2. Iterate through each element in the list:
- - If count is 0, update the candidate to the current element and set count to 1.
- - If the current element matches the candidate, increment the count.
- - If the current element does not match the candidate, decrement the count.
- 3. The candidate at the end of the iteration will be the majority element.
- Why This Works:
- - The algorithm pairs each candidate element with a different element and cancels them out.
- - If an element appears more than half the time (majority), it will survive the cancellation process.
- - Even if the candidate is replaced during the process, the final candidate will be the true majority
- due to its dominance.
- """
- candidate = None
- count = 0
- for num in nums:
- if count == 0:
- candidate = num
- count += 1
- continue
- count = count + 1 if candidate == num else count - 1
- return candidate
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement