美文网首页
【1对1错0】构建乘积数组

【1对1错0】构建乘积数组

作者: 7ccc099f4608 | 来源:发表于2019-01-27 15:27 被阅读0次

    https://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46?tpId=13&tqId=11204&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
    | 日期 | 是否一次通过 | comment |
    |----|----|----|
    |2019-01-26 13:20|N|暴力循环需要O(n^2),然而分词遍历,则只需要2*O(n)|
    |2019-01-27 13:20|Y||

    题目:给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]A[1]...A[i-1]A[i+1]...A[n-1]。不能使用除法。

    image.png

    图片来源:https://www.nowcoder.com/questionTerminal/94a4d381a68b47b7a8bed86f2975db46

    1.非递归

    public class Solution {
        public int[] multiply(int[] A) {
            int[] result = new int[A.length];
            result[0] = 1;
            for(int i=1; i<A.length; i++) {
                result[i] = result[i-1] * A[i-1];
            }
            
            int tempM = 1;
            for(int j = A.length-2; j>=0; j--) {
                tempM *= A[j+1];
                result[j] *= tempM;
            }
            
            return result;
        }
    }

    相关文章

      网友评论

          本文标题:【1对1错0】构建乘积数组

          本文链接:https://www.haomeiwen.com/subject/wfagjqtx.html