Skip to content

Latest commit

 

History

History
124 lines (97 loc) · 2.59 KB

File metadata and controls

124 lines (97 loc) · 2.59 KB

题目描述

给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B[i] 的值是数组 A 中除了下标 i 以外的元素的积, 即 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。

 

示例:

输入: [1,2,3,4,5]
输出: [120,60,40,30,24]

 

提示:

  • 所有元素乘积之和不会溢出 32 位整数
  • a.length <= 100000

解法

B[i] = (A[0] * A[1] * ... * A[i-1]) * (A[i+1] * ... * A[n-1])

Python3

class Solution:
    def constructArr(self, a: List[int]) -> List[int]:
        n = len(a)
        output = [1] * n
        left = right = 1
        for i in range(n):
            output[i] = left
            left *= a[i]
        for i in range(n - 1, -1, -1):
            output[i] *= right
            right *= a[i]
        return output

Java

class Solution {
    public int[] constructArr(int[] a) {
        int n = a.length;
        int[] output = new int[n];
        for (int i = 0, left = 1; i < n; ++i) {
            output[i] = left;
            left *= a[i];
        }
        for (int i = n - 1, right = 1; i >= 0; --i) {
            output[i] *= right;
            right *= a[i];
        }
        return output;
    }
}

JavaScript

/**
 * @param {number[]} a
 * @return {number[]}
 */
var constructArr = function (a) {
    const n = a.length;
    let output = new Array(n);
    for (let i = 0, left = 1; i < n; ++i) {
        output[i] = left;
        left *= a[i];
    }
    for (let i = n - 1, right = 1; i >= 0; --i) {
        output[i] *= right;
        right *= a[i];
    }
    return output;
};

C#

public class Solution {
    public int[] ConstructArr(int[] a) {
        int n = a.Length;
        int[] ans = new int[n];
        int left = 1, right = 1;
        for (int i = 0; i < n; i++) {
            ans[i] = left;
            left *= a[i];
        }
        for (int i = n - 1; i > -1; i--) {
            ans[i] *= right;
            right *= a[i];
        }
        return ans;
    }
}

...