多数元素不计算元素

Majority Element not counting elements?

本文关键字:元素 计算      更新时间:2023-10-16

>假设我们有这 2 个数据数组

{ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,

4, 4, 5 }

{ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4

, 4 }

在我找出候选元素后,我创建了一个函数,然后确定该候选元素是否确实是数组中的多数元素。对于第一个数组示例,它工作得很好,但对于第二个数组示例则不然。

for (int i = 0; i < sz; i++){
    if (arr[i] == mElement){
        count++;
    }
}
if (count> sz/2){
    majority = mElement;
    return true;
}
else{
    return false;
}

对于第二个数组,多数元素显然应该是 4,但我的代码一直返回 5。在他计数命中 10 后,它应该切换到查看 4 是否是多数元素。

任何人都可以帮助并指出我的方向来帮助我解决这个问题吗?非常感谢!

您将需要跟踪您看到每个数字的次数。此问题的最佳解决方案使用哈希映射。

我不确定你在哪里确定mElement的值。您的代码如何知道在 10 时切换到 4 作为多数元素。在执行的这一点上,它无法知道数组其余部分有哪些数字。

 int max_element( const vector<int>& arr ){
     map<int, int> total;
     for( int i = 0; i < arr.size(); i++){
         total[arr[i]]++;
     }
     int cur_max = 0;
     int max_num = 0;
     for( auto it = total.begin(); it != total.end(); ++it){
         if ( it->second > cur_max ){
             cur_max = it->second;
             max_num = it->first;
         }
     }
     return max_num;
 }

这每次都有效