-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathBoyerMooreMajorityVote.cs
More file actions
45 lines (38 loc) · 1.11 KB
/
BoyerMooreMajorityVote.cs
File metadata and controls
45 lines (38 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
namespace Algorithms.Other;
/// <summary>
/// Boyer-Moore Majority Vote algorithm.
/// Finds element appearing more than n/2 times in O(n) time, O(1) space.
/// </summary>
public static class BoyerMooreMajorityVote
{
/// <summary>
/// Finds the majority element.
/// </summary>
/// <param name="nums">Input array.</param>
/// <returns>Majority element or null.</returns>
public static int? FindMajority(int[] nums)
{
if (nums == null || nums.Length == 0)
{
return null;
}
var candidate = FindCandidate(nums);
return IsMajority(nums, candidate) ? candidate : null;
}
private static int FindCandidate(int[] nums)
{
int candidate = nums[0];
int count = 1;
for (int i = 1; i < nums.Length; i++)
{
if (count == 0)
{
candidate = nums[i];
}
count += nums[i] == candidate ? 1 : -1;
}
return candidate;
}
private static bool IsMajority(int[] nums, int candidate) =>
nums.Count(n => n == candidate) > nums.Length / 2;
}