leetcode66构建乘积数组

 

思路:

       1,需要两个for循环

          实现:b[0]=1,b[1]=1*a[0],b[2]=1*a[0]*a[1],b[3]=1*a[0]*a[1]*a[2],b[4]=1*a[0]*a[1]*a[2]*a[3]

          另一个for循环实现:

          b[4]=1,b[3]=1*b[4],b[2]=1*b[4]*b[3],b[1]=1*b[4]*b[3]*b[2],b[0]=1*b[4]*b[3]*b[2]*b[1]

          两个合起来就是此题的解

 public int[] constructArr(int[] a) {   
        int len =a.length;   
     int [] b =new int [len];
     for(int i=0,product=1;i<len;product*=a[i],i++){
         b[i]=product;
     }
     for(int j=len-1,product=1;j>=0;product*=a[j],j--){
         b[j]*=product;
     }
     return b;
    }
}

 


版权声明:本文为qq_37244548原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。