一、问题描述
求数组中比左边元素都大同时比右边元素都小的元素,返回这些元素的索引
二、第一次实现
1.算法描述
本例将所有返回元素存放在一个数组中,用结构体返回数组的起始地址和元素个数
2.源代码
结构体定义:
typedef struct{
int* ArrayAddress;
int LengthOfArray;
}output;
主函数:
main()
{
output* output1;
int a[] = { 1, 2, 3, 1, 5, 6, 7, 9 };
int i = 0;
output1 = find(a, (sizeof(a)/sizeof(a[0])));
for (i = 0; i < (output1->LengthOfArray); i++)
{
printf("%d\t", *(output1->ArrayAddress++));
}
}
功能函数
output* find(int* Array, int ArraySize)
{
int *SaveOut=NULL, *SaveOutP = NULL;
int i = 0;
output* output1;
output1 = (output*)malloc(sizeof(output));
SaveOut = (int*)malloc(ArraySize * sizeof(SaveOut));
/*initialize the SaveOut*/
for (i = 0; i < ArraySize; i++)
{
SaveOut[i] = 0;
}
SaveOutP = SaveOut;
for (i = 1; i < ArraySize; i++)
{
/*Start traversing every element of Array;
*Saving every bigger number to the element pointed by SaveOutP when traversing and move forward the SaveOutP and Array[i];
*but if you encounter a lower than it ,you should clear the element pointed to by the pointer SaveOutP and let SaveOutP move a step back (Array[i] keep itself)
*/
/*Move forward*/
if (*(Array+i) > *(Array+*SaveOutP))
{
SaveOutP++;
*SaveOutP = i;
}
/*Move back*/
else
{
while ((*(Array + i) <= *(Array + *SaveOutP)) & (SaveOutP != SaveOut))
{
*SaveOutP = 0;
SaveOutP--;
}
}
}
SaveOutP = SaveOut;
while (*(++SaveOutP))
{
}
output1->ArrayAddress = SaveOut + 1;
output1->LengthOfArray = SaveOutP - SaveOut - 2;
return output1;
}
三、改进提示
我们先假设一个数组中有两个元素x和y满足题目条件,且再假设a是小于x的元素块,b是介于x和y之间的元素块,c是大于y的元素块,则可以证明若x和y满足条件,那么元素块b也满足条件,所以说满足题目条件的元素的所以是一系列连续的整数值