构建乘积数组

构建乘积数组

http://www.nowcoder.com/questionTerminal/94a4d381a68b47b7a8bed86f2975db46

思路:设置两个数组pre,post;前者保存i之前的所有乘积,后者保存i之后的所有乘积;为了计算方便pre【0】=1;post【A.length-1】=1
那么B【i】=pre【i】*post【i】

 public static int[] multiply(int[] A) {
        if(A.length<2)return null;
        int[] pre = new int[A.length];
        pre[0]=1;
        int[] post = new int[A.length];
        post[A.length-1]=1;
        int[] res  = new int[A.length];
        for (int i = 1; i <A.length ; i++) {
            pre[i]=pre[i-1]*A[i-1];

        }
        for (int i = A.length-2; i>=0 ; i--) {
            post[i]=post[i+1]*A[i+1];

        }

        for (int i =0;i<A.length;i++){
            res[i]=pre[i]*post[i];
        }
        return res;
    }
全部评论
可以不使用额外数组,一开始没想到
点赞 回复 分享
发布于 2020-02-23 03:09

相关推荐

被加薪的哈里很优秀:应该继续招人,不会给你留岗位的
点赞 评论 收藏
分享
frutiger:逆天,我家就安阳的,这hr咋能说3k的,你送外卖不比这工资高得多?还说大厂来的6k,打发叫花子的呢?这hr是怎么做到说昧良心的话的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务