函数返回排序数组中重复数字的计数
Function to return count of duplicate numbers in sorted array
我想返回排序数组中重复值的数量。
例如:a={1,1,2,3,4,4},fratelli(n)应该返回2。(它们是1,1和4,4)
我试图使用递归方法,但它不起作用。它总是给我4。
我想问是否有人能帮助我更好地理解这种编程方法。非常感谢!
功能:
#include <iostream>
using namespace std;
int fratelli(int a[], int l, int r)
{
if (l == r) return 0;
else
{
int c = (l+r) / 2;
int n = fratelli(a, l, c) + fratelli(a, c+1, r);
if (a[l] == a[l+1]) n++;
return n;
}
}
int main()
{
const int _N = 11;
int array[_N] = { 1, 1, 2, 3, 5, 5, 7, 8, 8, 11, 12 };
cout << "n" << fratelli(array, 0, _N-1);
return 0;
}
您在这一行有一个错误:
if (a[l] == a[l+1]) n++;
检查应该在索引c
处,而不是在l
处。除此之外,你的代码对我来说似乎还可以。
相关文章:
- 函数如何使用引用返回所需的数字?
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- 返回 int 中可被 2 c++ 整除的所有数字的总和
- C++ python 中的函数返回数字而不是字符串
- 使用非托管导出将字符串从 C# 返回到C++将返回数字
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 将 MPFR 数字转换为字符串并返回
- C++ 递归:返回数字的最小偶数
- typeid.name 返回派生类类型之前的数字
- Fibbonaci 递归代码返回错误值,始终返回下一个数字
- 为什么我的阶乘数查找器返回以C++输入的数字?(已编辑)
- 尝试编写函数尝试从字符串中提取数字,但它返回不相关的数字
- 随机函数在循环中调用时返回相同的数字!C++
- 将字符转换为ASCII返回数字太大
- 为什么此范围基于语句返回一个数字太低的范围
- 根据另一个数字的可整除性返回子数组中的索引
- 如果数组中有重复的数字,如何返回'false'?
- 递归计算满足条件的值数并返回该数字
- C++余数以较高的数字返回 7