2012腾讯实习招聘笔试附加题1求解方法

附加题1:问题描述大致如下:

一个数组a[n],求构造出一个b[n],使得b[i]=a[0]*a[1]*...a[n-1]/a[i];不能用除法,除了循环变量外 不能用额外的变量 ,要求O(1)的空间复杂度,O(n)的时间复杂度。

首先我对题目是有点疑问的:题目所说的O(1)的空间复杂度,那么意思是:

1、b数组占用的空间是原来a的空间?

2、还是b另外申请一个数组空间,而不用包括在O(1)中呢?

对于第一种假设,本身愚钝,万想不得其解,希望各位高手给予指点

对于第二种假设,自己实现代码余下:

想了N久自己写下如下代码:

publicclass TecentTest {

publicvoid change(int[] a, int[] b) {

b[0] = 1;

int temp = 1;

for (int i = 1; i < a.length; i++) {/* b[i]表示0-->i-1的乘值 */

temp = temp * a[i - 1];

b[i] = temp;

}

temp = 1;

for (int j = a.length- 2; j >= 0; j--) {

temp = temp * a[j+1];/*temp记录j+1-->n-1的乘值*/

b[j]=b[j]*temp; /* b[j]结果值 */

}

b[a.length - 1] = b[a.length - 1];

}

publicstaticvoid main(String[] args) {

TecentTest tt = new TecentTest();

int[] a = { 1, 2, 3, 4, 5,6 };

int[] b =newint[a.length];

tt.change(a, b);

for (int i = 0; i < b.length; i++) {

System.out.print(b[i] +" ");

}

}

}

/*测试结果:

* 720 360 240 180 144 120

* */

以上代码空间复杂度O(1),时间复杂度O(n)

小弟不才,违背了题目“除了循环变量外 不能用额外的变量”的条件,不知道怎样改进,希望各位高手来指点指点,谢谢先!

另一个网友的解法:

public class TencentTest {

    public void change(int[] a, int[] b) {

       b[0] = 1;

//       int temp = 1;

       for (int i = 1; i < a.length; i++) {/* b[i]表示0-->i-1的乘值 */

//           temp = temp * a[i - 1];

//           b[i] = temp;
    	   b[i] = b[i-1]*a[i-1];
       }

//       temp = 1;
       a[0] = 1;
       for (int j = a.length - 2; j >= 0; j--) {

//           temp = temp * a[j+1];/*temp记录j+1-->n-1的乘值 */
//
//           b[j]=b[j]*temp;     /* b[j]结果值 */
    	   a[0] = a[0]*a[j+1];
    	   b[j] = b[j]*a[0];

       }
//       b[a.length - 1] = b[a.length - 1];

    }

    public static void main(String[] args) {

       TencentTest tt = new TencentTest();

       int[] a = { 1, 2, 3, 4, 5,6 };

       int[] b =new int[a.length];

       tt.change(a, b);

       for (int i = 0; i < b.length; i++) {

           System.out.print(b[i] +" ");

       }

    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值