多数元素不计算元素
Majority Element not counting elements?
>假设我们有这 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;
}
这每次都有效
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 我必须计算方阵的对角线元素之和的差值
- 如何计算地图中重复元素/值的数量?
- 如何计算字符串中用户输入元素的出现次数?
- 我正在尝试计算链表中当前元素的数量
- 如何计算单个元素在向量<float>中所有元素之和中的百分比
- 如何计算大小为 1000 x 1000 的 2D 数组中 2 个元素之间的步幅?C++
- 如何在 c++ 中计算相同数组元素的数量
- 计算向量中大于数字的元素
- 如何在 c++ 中计算 2 个不同向量的相等元素
- 我写了这个简单的代码,应该计算一系列数组元素的最高数量,但结果很奇怪
- 计算TXT文件中元素的数量
- 从右到左计算当前索引中的数据结构中的元素数,并打印每个元素的计数
- 根据堆栈操作 c++ 计算元素的最大数量
- 对懒惰元素懒洋洋地计算的矢量进行排序
- 计算第一个和最后一个元素绝对差值较小的子序列 <= K
- 如何在多维数组中搜索单个行,然后对某些行中的每个单个元素执行计算
- 动态和静态分配数组元素计算
- 使用多个元素计算排列