兩個數組a[N],b[N],其中A[N]的各個元素值已知,現給b[i]賦值

來源:互聯網
上載者:User

題目:

兩個數組a[N],b[N],其中A[N]的各個元素值已知,現給b[i]賦值,b[i] = a[0]*a[1]*a[2]...*a[N-1]/a[i];
要求:
1.不準用除法運算
2.除了迴圈計數值,a[N],b[N]外,不準再用其他任何變數(包括局部變數,全域變數等)
3.滿足時間複雜度O(n),空間複雜度O(1)

分析:

好久沒做題了,這次做一個比較簡單的題,由於題目要求不能使用其他額外的局部變數和全域變數(當然除了計數器比變數),可以考慮使用b[0]儲存,迴圈兩次,其中:

b[i] = a[0] *a[1] * a[2] … a[i-1] *
a[i+1] * a[i+2] * … a[N-2] * a[N -1]

可以先計算前面紅色部分,再計算後面藍色部分。

代碼如下:

#include<iostream>using namespace std;int main(){int a[] = {1,2,3,4,5,6,7,8};int b[] = {1,1,1,1,1,1,1,1};int len = sizeof(a) / sizeof(a[0]);for(int i = 1; i <= len - 1; i++)//b[i]儲存b[0 ... i-1]的資料{b[i] = b[i-1] * a[i-1];}for(int i = len - 1; i > 0; i--){b[0] = b[0] * a[i];//b[0]儲存b[i+1 。。。 len-1]資料if(i - 1 != 0)//這裡需要注意,判斷是否到達開始位置b[i - 1] *= b[0];//將資料相乘儲存起來}for(int i = 0; i < len; i++)cout << b[i] << " ";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.