忘我之乘积的解答

 
 
Q: Given array a [n], Get array b [n] b [i] = a [0] * a [1] ... a [n-2] * a [n-1] / a [i]

Requirements can not be used to divide
In addition to traverse the counter with a [N] b [N], do not use the new variable
(including stack temporary variables, space and global static variable)
Space complexity of O (1) time complexity of O (n)


    
    
/*
arr_b[0] = a[1]*a[2]*a[3]*a[4]
arr_b[1] = a[0]* a[2]*a[3]*a[4]
arr_b[2] = a[0]*a[1]* a[3]*a[4]
arr_b[3] = a[0]*a[1]*a[2]* a[4]
arr_b[4] = a[0]*a[1]*a[2]*a[3]
*/

const int ARRLEN = 5;
int arr_a[ARRLEN] = {1, 2, 3, 4, 5}; 
int arr_b[ARRLEN];

void solve_2(int arr[], int len){
	int index = 0;

	// loop from begin to end
	arr_b[0] = 1;
	for (index = 1; index < len; ++index){
		arr_b[index] = arr_b[index - 1]*arr_a[index - 1]; 
	}

	// loop from end to begin
	for (index = len-2; index > 0; --index){
		arr_b[0] *= arr_a[index + 1];
		arr_b[index] *= arr_b[0];
	}
	arr_b[0] *= arr_a[1];

	copy(arr_b, arr_b+len, ostream_iterator<int>(cout, " "));
}




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值