18 Star 133 Fork 63

编程语言算法集 / C-Sharp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
BoyerMoore.cs 1.40 KB
一键复制 编辑 原始数据 按行查看 历史
Gerson Jr 提交于 2023-12-31 09:48 . Switch to file-scoped namespaces (#431)
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Search;
/// <summary>
/// A Boyer-Moore majority finder algorithm implementation.
/// </summary>
/// <typeparam name="T">Type of element stored inside array.</typeparam>
public static class BoyerMoore<T> where T : IComparable
{
public static T? FindMajority(IEnumerable<T> input)
{
var candidate = FindMajorityCandidate(input, input.Count());
if (VerifyMajority(input, input.Count(), candidate))
{
return candidate;
}
return default(T?);
}
// Find majority candidate
private static T FindMajorityCandidate(IEnumerable<T> input, int length)
{
int count = 1;
T candidate = input.First();
foreach (var element in input.Skip(1))
{
if (candidate.Equals(element))
{
count++;
}
else
{
count--;
}
if (count == 0)
{
candidate = element;
count = 1;
}
}
return candidate;
}
// Verify that candidate is indeed the majority
private static bool VerifyMajority(IEnumerable<T> input, int size, T candidate)
{
return input.Count(x => x.Equals(candidate)) > size / 2;
}
}
C#
1
https://gitee.com/TheAlgorithms/C-Sharp.git
git@gitee.com:TheAlgorithms/C-Sharp.git
TheAlgorithms
C-Sharp
C-Sharp
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891