Find the most common entry in an array

前端 未结 8 1985
终归单人心
终归单人心 2020-12-07 10:43

You are given a 32-bit unsigned integer array with length up to 232, with the property that more than half of the entries in the array are equal to N, for some 32

8条回答
  •  执笔经年
    2020-12-07 11:06

    You can do this with only two variables.

    public uint MostCommon(UInt32[] numberList)
    {
        uint suspect = 0;
        int suspicionStrength = -1; 
        foreach (uint number in numberList)
        {
            if (number==suspect)
            {
                suspicionStrength++;
            }
            else
            {
                suspicionStrength--;
            }
    
            if (suspicionStrength<=0)
            {
                suspect = number;
            }
        }
        return suspect;
    }
    

    Make the first number the suspect number, and continue looping through the list. If the number matches, increase the suspicion strength by one; if it doesn't match, lower the suspicion strength by one. If the suspicion strength hits 0 the current number becomes the suspect number. This will not work to find the most common number, only a number that is more than 50% of the group. Resist the urge to add a check if suspicionStrength is greater than half the list length - it will always result in more total comparisons.

    P.S. I have not tested this code - use it at your own peril.

提交回复
热议问题