Fra*_*zzi 0 c++ algorithm recursion divide-and-conquer
我想返回排序数组中重复值的数量.
例如: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;
}
Run Code Online (Sandbox Code Playgroud)
你在这一行上有错误:
if (a[l] == a[l+1]) n++;
Run Code Online (Sandbox Code Playgroud)
检查应该是索引c而不是l.除此之外,你的代码对我来说似乎没问题.