給定數組a[N]構造數組b [N]——騰訊筆試

來源:互聯網
上載者:User

給定一個數組a[N],我們希望構造數組b [N],其中b[j]=a[0]*a[1]…a[N-1]
/ a[j],在構造過程中,不允許使用除法:要求O(1)空間複雜度和O(n)的時間複雜度;除遍曆計數器與a[N]
b[N]外,不可使用新的變數(包括棧臨時變數、堆空間和全域靜態變數等)

 

解析:設b[0]=1

由b[i]=b[i-1]*a[i-1]可得

b[1] = a[0]

b[2] = a[0]a[1]

b[i] = a[0]a[1]a[2]…a[i-1]

b[n-1] = a[0]a[1]…a[n-2]

那麼再通過b[0]這個變數來迭代出1, a[n-1], a[n-2]a[n-1], a[n-3]a[n-2]a[n-1], … , a[1]a[2]a[3]…a[n-1],迭代過程中分別乘以b[n-1], b[n-2],
… , b[0]

代碼如下

void Translate(int a[], int b[], int n){b[0] = 1;for (int i = 1; i <= n-1; i++){b[i] = b[i-1]*a[i-1];}for (int i = n-1; i >= 1; i--){b[i] *= b[0];b[0] *= a[i];}}

 

測試代碼如下

int main(){int a[] = {2,3,4,5};int b[] = {0,0,0,0};Translate(a,b,4);for(int i = 0; i < 4; i++)cout << a[i] << "\t";cout << endl;for(int i = 0; i < 4; i++)cout << b[i] << "\t";cout << endl;system("pause");return 0;}

 

結果如下


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.