Array of size n, with one element n/2 times

前端 未结 9 690
离开以前
离开以前 2021-02-04 12:41

Given an array of n integers, where one element appears more than n/2 times. We need to find that element in linear time and constant extra space.

YAAQ: Yet another arra

9条回答
  •  孤城傲影
    2021-02-04 13:12

    I have a sneaking suspicion it's something along the lines of (in C#)

    // We don't need an array
    public int FindMostFrequentElement(IEnumerable 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;
    }
    

    It sounds unlikely to work, but it does. (Proof as a postscript file, courtesy of Boyer/Moore.)

提交回复
热议问题