algorithm - 大小为 n 的数组,一个元素 n/2 次

标签 algorithm

给定一个包含 n 个整数的数组,其中一个元素出现了 n/2 次以上。我们需要在线性时间和常量额外空间中找到该元素。

YAAQ:又一个数组问题。

最佳答案

我暗暗怀疑它与(在 C# 中)类似

// We don't need an array
public int FindMostFrequentElement(IEnumerable<int> sequence)
{
    // Initial value is irrelevant if sequence is non-empty,
    // but keeps compiler happy.
    int best = 0; 
    int count = 0;

    foreach (int element in sequence)
    {
        if (count == 0)
        {
            best = element;
            count = 1;
        }
        else
        {
            // Vote current choice up or down
            count += (best == element) ? 1 : -1;
        }
    }
    return best;
}

这听起来不太可能奏效,但确实如此。 (Proof as a postscript file,由博耶/摩尔提供。)

关于algorithm - 大小为 n 的数组,一个元素 n/2 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/744981/

相关文章:

python - 如何从 python 字典键创建对

algorithm - 机械臂绘画笔画生成算法

c++ - 比较存储在 mysql 数据库中的 SIFT 特征

javascript - 递归回溯生成迷宫

c++ - 如何化简两个相似的函数

c# - 检查数组中的多个元素是否包含相同的值

algorithm - 线段与凸多边形的交集

algorithm - MATLAB 中基于图像的视觉伺服算法

algorithm - 计算树高提供了左树高和右树高的条件

java - 在 Java 中每秒重复访问数组项