`
我是小仙321
  • 浏览: 13105 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

一道笔试题

    博客分类:
  • Java
 
阅读更多

题目:给定一个数组a[N],我们希望构造数组b[N],其中b[i]=a[0]*a[1]*...*a[N-1]/a[i]。在构造过程:不允许使用除法;

要求O(1)空间复杂度和O(n)时间复杂度;

除遍历计数器与a[N] b[N]外,不可使用新的变量(包括栈临时变量、对空间和全局静态变量等);

请用程序实现并简单描述。

public class ArrayTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] a={1,2,3,4};
		int[] b=new ArrayTest().getArray(a);
		for(int k=0;k<a.length;k++){
		System.out.print(b[k]+" ");
		}

	}
	private int[] getArray(int[] a){
		int[] b=new int[a.length];
		b[0]=1;
		for(int i=1;i<a.length;i++){
			b[i]=b[i-1]*a[i-1];
		}
		for(int j=a.length-1;j>1;j--){
			b[0]*=a[j];
			b[j-1]*=b[0];
		}
		b[0]*=a[1];
		return b;
	}

}

 

1
5
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics