首先來看題目描述:
三 、加分題
28)給定一數組a[N],我們希望構造數組b [N],其中b[j]=a[0]*a[1]…a[N-1] / a[j],在構造過程中,不允許使用除法:
要求O(1)空間複雜度和O(n)的時間複雜度;
除遍歷計數器與a[N] b[N]外,不可使用新的變量(包括棧臨時變量、堆空間和全局靜態變量等);
實現程序(主流編程語言任選)實現並簡單描述。
這道題目最爲獨特的要求就是除去遍歷計算器外不能申請其它新的變量。怎麼解決了?首先不考慮這個條件,代碼如下:
- // 騰訊2012年實習生筆試加分題
- //http://blog.csdn.net/morewindows/article/details/8742666
- //By MoreWindows( http://blog.csdn.net/MoreWindows )
- #include <stdio.h>
- void PrintfArray(int a[], int n)
- {
- for (int i = 0; i < n; i++)
- printf("%5d ", a[i]);
- putchar('\n');
- }
- int main()
- {
- printf(" 騰訊2012年實習生筆試加分題 \n");
- printf(" - http://blog.csdn.net/morewindows/article/details/8742666 -\n");
- printf(" -- By MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
- const int MAXN = 5;
- int a[MAXN] = {1, 3, 5, 7, 9};
- int b[MAXN];
- printf("數組a爲:\n");
- PrintfArray(a, MAXN);
- b[0] = 1;
- int i;
- for (i = 1; i < MAXN; i++)
- b[i] = b[i - 1] * a[i - 1];
- int temp = 1;
- for (i = MAXN - 2; i >= 0; i--)
- {
- temp *= a[i + 1];
- b[i] *= temp;
- }
- printf("數組b爲:\n");
- PrintfArray(b, MAXN);
- return 0;
- }
// 騰訊2012年實習生筆試加分題
//http://blog.csdn.net/morewindows/article/details/8742666
//By MoreWindows( http://blog.csdn.net/MoreWindows )
#include <stdio.h>
void PrintfArray(int a[], int n)
{
for (int i = 0; i < n; i++)
printf("%5d ", a[i]);
putchar('\n');
}
int main()
{
printf(" 騰訊2012年實習生筆試加分題 \n");
printf(" - http://blog.csdn.net/morewindows/article/details/8742666 -\n");
printf(" -- By MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
const int MAXN = 5;
int a[MAXN] = {1, 3, 5, 7, 9};
int b[MAXN];
printf("數組a爲:\n");
PrintfArray(a, MAXN);
b[0] = 1;
int i;
for (i = 1; i < MAXN; i++)
b[i] = b[i - 1] * a[i - 1];
int temp = 1;
for (i = MAXN - 2; i >= 0; i--)
{
temp *= a[i + 1];
b[i] *= temp;
}
printf("數組b爲:\n");
PrintfArray(b, MAXN);
return 0;
}
解釋下代碼,設有數組大小爲5。
對於第一個for循環
第一步:b[0] = 1;
第二步:b[1] = b[0] * a[0] = a[0]
第三步:b[2] = b[1] * a[1] = a[0] * a[1];
第四步:b[3] = b[2] * a[2] = a[0] * a[1] * a[2];
第五步:b[4] = b[3] * a[3] = a[0] * a[1] * a[2] * a[3];
然後對於第二個for循環
第一步
temp *= a[4] = a[4];
b[3] = b[3] * temp = a[0] * a[1] * a[2] * a[4];
第二步
temp *= a[3] = a[4] * a[3];
b[2] = b[2] * temp = a[0] * a[1] * a[4] * a[3];
第三步
temp *= a[2] = a[4] * a[3] * a[2];
b[1] = b[1] * temp = a[0] * a[4] * a[3] * a[2];
第四步
temp *= a[1] = a[4] * a[3] * a[2] * a[1];
b[0] = b[0] * temp = a[4] * a[3] * a[2] * a[1];
由此可以看出從b[4]到b[0]均已經得到正確計算。
運行結果如下所示(圖片無法打開?請訪問http://blog.csdn.net/morewindows/article/details/8742666):
然後考慮到題目要求不能申請額外的臨時變量,因此int temp肯定是不能有的,那用什麼來代替這個temp了?很簡單,用b[0]來代替即可。於是上面的第二個for循環語句變爲:
- for (i = MAXN - 1; i >= 1; i--)
- {
- b[i] *= b[0];
- b[0] *= a[i];
- }
for (i = MAXN - 1; i >= 1; i--)
{
b[i] *= b[0];
b[0] *= a[i];
}
試驗下,運行結果如下所示(圖片無法打開?請訪問http://blog.csdn.net/morewindows/article/details/8742666):
呵呵,b[0]一代替,輕輕鬆鬆加分到手^_^。有其它方法歡迎交流(http://weibo.com/MoreWindows Or [email protected]),謝謝。
地址:http://blog.csdn.net/morewindows/article/details/8742666轉載請標明出處,謝謝。
歡迎關注微博:http://weibo.com/MoreWindows