Mid
From PDF
Coding
C# Coding Interview
Find Majority Element (More than n/2 times)?
int MajorityElement(int[] nums)
{
int count = 0, candidate = 0;
foreach (var num in nums)
{
if (count == 0)
candidate = num;
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
Explanation:
Boyer-Moore Voting Algorithm tracks majority element by counting net votes.
Follow on:
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png