Given an array a [N], we want to construct array B [N], where B [j] = a [0] * a [1]… A [N-1]
/A [j], division is not allowed in the construction process: requires O (1) space complexity and O (n) time complexity; in addition to traversing the counter and a [N]
New variables (including stack temporary variables, heap space and global static variables) cannot be used outside B [N)
Resolution: Set B [0] = 1
Available from 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]
Then, through the variable B [0] To iterate out 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], multiplied by B [n-1], B [N-2],
... , B [0]
The Code is as follows:
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];}}
The test code is as follows:
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;}
The result is as follows: