This question already has answers here:
How to find the element of an array that is repeated at least N/2 times?
                                
                                    (8个答案)
                                
                        
                                5年前关闭。
            
                    
我有一个由5个字符串组成的数组,我希望能够将字符串彼此进行比较,以找出是否存在多数,然后返回该多数。因此,如果:

a[0] = "dog";
a[1] = "dog";
a[2] = "dog";
a[3] = "dog";
a[4] = "cat";


我想归还“狗”。在像2个相同,2个相同和1个这样的情况下,我希望它返回“不占多数”。有没有一种方法,而无需大量的if语句,换句话说就是优雅的方法?

最佳答案

您可以使用字典:

std::unordered_map<std::string, unsigned int> historgram;
std::string most_popular;
unsigned int m = 0;
bool unique = false;

for (s : a)
{
    unsigned int & i = histogram[s];
    ++i;
    if (i == m) { unique = false; }
    else if (i > m) { unique = true; m = i; most_popular = s; }
}

return unique ? most_popular : "no majority"'

09-11 17:02