假定函数的输入参数是数组指针和数组内的元素个数,我想到两种方法:由于输入数据一般是只读的形式,所以需要在函数内部申请一块内存区域,以便于算法的展开。第一种方法利用了数值排序和“数值跳变的边沿”来计算,第二种则使用了数值替换/填充的方式来计算。
执行结果如上图,完整代码如下,供大家“板”我,呵呵~~
//-----------------------------------------------------------------------------------------------------------------------------------------------------
#include "stdafx.h"
#include <iostream>
#include <malloc.h>
using namespace std;
int TestArray[20] = {3,103,2,4,3,6,4,7,8,8,3,4,6,1,34,7,38,2,4,10};
void PrintArray(int *a)
{
int i=0;
for (i=0;i<20;i++)
{
printf("%d ",*(a+i));
}
printf("\n");
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
int DifDetWay1(int *A, int n)
//int DifDetWay1(int *A, int *B, int n)
{
int i = 0x00;
int j = 0x00;
int Temp;
int Cal;
int Flag;
Temp = A[0];
int *B = (int *)malloc(20 * sizeof(int));
if (B != NULL)
{
for(i=0;i<n;i++)
{
*(B+i) = A[i];
}
PrintArray(B);
//
for(i=0;i<n;i++)
{
Flag = 0x00;
for(j=1;j<n;j++)
{
if(B[j-1]>B[j])
{
Temp = B[j-1];
B[j-1] = B[j];
B[j] = Temp;
Flag = 0x01;
}
}
if (Flag != 0x01)
{
break;
}
else
{
}
}
PrintArray(B);
//
Temp = B[0];
Cal = 0x01;
for(i=0;i<n;i++)
{
if(Temp != B[i])
{
Cal++;
}
else
{
}
Temp = B[i];
}
free(B);
//printf( "Memory freed\n" );
}
return(Cal);
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
int DifDetWay2(int *A, int n)
{
int i = 0x00;
int j = 0x00;
int Temp;
int Cal = 0x00;
int *B = (int *)malloc(20 * sizeof(int));
if (B != NULL)
{
for(i=0;i<n;i++)
{
B[i] = A[i];
}
PrintArray(B);
printf("\n");
Cal++;
Temp = B[0];
for(i=1;i<n;i++)
{
if(B[i] != B[0])
{
Temp = B[i];
Cal++;
for(j=i;j<n;j++)
{
if(B[j] == Temp)
{
B[j] = B[0];
}
}
PrintArray(B);
}
}
free(B);
//printf( "Memory freed\n" );
}
return(Cal);
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
int num = 0x00;
printf("\n----------DifDetWay1\n");
num = DifDetWay1(TestArray,20);
printf(" %d \n",num);
printf("\n--------DifDetWay2\n");
num = DifDetWay2(TestArray,20);
printf(" %d \n",num);
return 0;
}