我想返回排序数组中重复值的数量。
例如: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
。除此之外,您的代码对我来说似乎还不错。
关于c++ - 返回排序数组中重复数字计数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17233609/