【问题标题】:Majority Element not counting elements?多数元素不计算元素?
【发布时间】:2016-06-03 00:34:33
【问题描述】:

假设我们有这两个数据数组

{ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 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 }

在找出候选者之后,我创建了一个函数,然后确定该候选者是否确实是数组中的多数元素。对于第一个数组示例,它可以完美运行,但对于第二个数组示例则不行。

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 是否是多数元素。

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

【问题讨论】:

标签: c++ arrays element


【解决方案1】:

您将想要跟踪您看到每个数字的次数。这个问题的最佳解决方案是使用 Hashmap。

我不确定您在哪里确定 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;
 }

这将每次都有效

【讨论】:

  • std::map 不是哈希映射,应该是 std::unordered_map
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 2017-08-23
  • 2018-04-16
相关资源
最近更新 更多