1、數組乘積(15分)
輸入:一個長度爲n的整數數組input
輸出:一個長度爲n的整數數組result,滿足result[i] = input數組中除了input[i]之外所有數的乘積(假設不會溢出)。比如輸入:input = {2,3,4,5},輸出result = {60,40,30,24}
程序時間和空間複雜度越小越好。
C/C++:
int *cal(int* input , int n);
Java:
輸入:一個長度爲n的整數數組input
輸出:一個長度爲n的整數數組result,滿足result[i] = input數組中除了input[i]之外所有數的乘積(假設不會溢出)。比如輸入:input = {2,3,4,5},輸出result = {60,40,30,24}
程序時間和空間複雜度越小越好。
C/C++:
int *cal(int* input , int n);
Java:
int[] cal(int[] input);
這道題看起來很簡單,許多人看完題目就會想到將所有的數相乘,得出總的乘機,然後再用總的乘機去分別處以input數組中的數就是要求的結果。
我們可以很容易的寫出下面的代碼:
int *cal(int *input,int n)
{
assert(input!=NULL && n>0);//注意判斷傳入參數的合法性
int i=0;
int prduct = 1;
int *result = new int[n];
if(result == NULL) //分配內存失敗,不要忘記釋放申請的堆內存
exit(0);
for(i=0; i<n; i++)
prduct *= input[i];
for(i=0; i<n; i++)
result[i] = prduct/input[i];
return result;
}
在測試時如果我們用的用例數組是這樣的{0,2,3,4},即數組中有1個或多個0時,程序就會在運行時崩潰,應爲我們得到的prduct的值是0.
下面是參考Hackbuteer1的這篇博客http://blog.csdn.net/hackbuteer1/article/details/8484974中給出的代碼,代碼略有改動,增加了程序的健壯性
int *cal(int *input,int n)
{
assert(input!=NULL && n>0);//注意判斷傳入參數的合法性
int i;
int *result = new int[n];
if(result == NULL) //分配內存失敗,不要忘記釋放申請的堆內存
exit(0);
result[0] = 1;
for(i=1; i<n; i++)
result[i] = result[i-1]*input[i-1];
result[0] = input[n-1];
for(i=n-2; i>0; i--)
{
result[i] *= result[0];
result[0] *= input[i];
}
return result;
}
一道小小的編程題,看似簡單,其實也不簡單。有時筆試面試時所出的編程題,出的題並不是很難,遇到這樣的題時要小心的是對程序輸入參數的檢查和問題考慮的是否全面!