以前找工作的时候去笔试搜狗遇到下面的题目,当时就崩溃了,呵呵,后来我在CSDN上发帖了。不过还是不懂。今天在网上看到了一个和这个问题差不多的问题。我决定一定要搞定它。苦思冥想了2小时加高人同事的提示,写出下面算法。
题目:
一个长度为n的数组a[0],a[1],...,a[n-1]。现在更新数组的各个元素,即a[0]变为a[1]到a[n-1]的积,a[1]变为a[0]和a[2]到a[n-1]的积,...,a[n-1]为a[0]到a[n-2]的积。最后返回更新后数组的最大值。程序要求:要求1.具有线性复杂度。2.不能使用除法运算符。算法:实际array[i]更新后的值为前array[0]~array[i-1]的积和array[i+1]~array[n-1]的积相乘。从前向后扫描一遍数组把前i个元素的积存在数组a中。从后向前扫描一遍数组把后n-i-1个元素的积存在数组b中。最后在扫描一遍数组更新值,其值为a中的前i个元素的积和b中的后n-i-1个元素的积相乘。
#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#define NUM 10
#define NEGATIVE_INF -10000
long MaxMultiple(long *arrayPtr, int n)
{
assert(arrayPtr != NULL && n != 0);
int itor;
long max = NEGATIVE_INF;
int *ptr1 = (int *)malloc(n * sizeof(int));
assert(ptr1 != NULL);
int *ptr2 = (int *)malloc(n * sizeof(int));
assert(ptr2 != NULL);
ptr1[0] = 1;
ptr2[n - 1] = 1;
for(itor = 1; itor < n; itor++)
{
ptr1[itor] = ptr1[itor - 1] * arrayPtr[itor - 1];
}
for(itor = n - 2; itor >= 0; itor--)
{
ptr2[itor] = ptr2[itor + 1] *arrayPtr[itor + 1];
}
for(itor = 0; itor < n; itor++)
{
arrayPtr[itor] =ptr1[itor] * ptr2[itor];
}
for(itor = 0; itor < n; itor++)
{
if(arrayPtr[itor] > max)
{
max = arrayPtr[itor];
}
}
free(ptr1);
free(ptr2);
return max;
}
int main()
{
long a[NUM] = {2,4,3,8,5,3,2,3,6,7};
int itor;
long max;
max = MaxMultiple(a,NUM);
printf("%d\n",max);
for(itor = 0; itor < NUM; itor++)
{
printf("%ld ",a[itor]);
}
printf("\n");
return 0;
}