【Lintcode】1415. Residual Product

記錄演算法發表於2020-12-09

題目地址:

https://www.lintcode.com/problem/residual-product/description

給定一個陣列 A A A,返回一個新陣列 B B B,使得 B [ i ] = ∏ j ≠ i A [ j ] B[i]=\prod_{j\ne i}A[j] B[i]=j=iA[j]。如果 A A A長度是 1 1 1則返回零陣列。

參考https://blog.csdn.net/qq_46105170/article/details/108656955。程式碼如下:

public class Solution {
    /**
     * @param arr: The array you should handle
     * @return: Return the product
     */
    public int[] getProduct(int[] arr) {
        // Write your code here
        int[] res = new int[arr.length];
        if (arr.length == 1) {
            return res;
        }
        
        long prod = 1;
        int zeroCount = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != 0) {
                prod *= arr[i];
            } else {
                zeroCount++;
            }
        }
        
        if (zeroCount == 1) {
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] == 0) {
                    res[i] = (int) prod;
                } else {
                    res[i] = 0;
                }
            }
        } else if (zeroCount == 0) {
            for (int i = 0; i < arr.length; i++) {
                res[i] = (int) (prod / arr[i]);
            }
        }
        
        return res;
    }
}

時間複雜度 O ( l A ) O(l_A) O(lA),空間 O ( 1 ) O(1) O(1)

相關文章