【數組】B075_LC_除自身以外數組的乘積(前綴積+後綴積 / 前後枚舉)

一、Problem

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Input:  [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

二、Solution

方法一:前綴積+後綴積

這是第一想法,該算法忽略了數組中的 0,而且使用了除法。

class Solution {
    public int[] productExceptSelf(int[] A) {
        int n = A.length, pre[] = new int[n+1], suf[] = new int[n+1];
        Arrays.fill(pre, 1);
        Arrays.fill(suf, 1);
        for (int i = 1; i <= n; i++) {
        	pre[i] = pre[i-1] * A[i-1];
        	suf[i] = suf[i-1] * A[n-i];
        }

        int[] a = new int[n];
        for (int i = 1; i <= n; i++) {
        	a[i-1] = (pre[i]/A[i-1]) * (suf[n-i]);
        }
        return a;
    }
}

對於邊界的掌控還是不是特別熟練,錯了一次並打印出來才知道邊界錯了。

class Solution {
    public int[] productExceptSelf(int[] A) {
        int n = A.length, pre[] = new int[n], suf[] = new int[n];
        pre[0] = 1;
        for (int i = 1; i < n; i++) {
        	pre[i] = pre[i-1] * A[i-1];
        }
		suf[n-1] = 1;
        for (int i = n-2; i >= 0; i--) {
        	suf[i] = suf[i+1] * A[i+1];
        }
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
        	a[i] = pre[i] * suf[i];
        }
        return a;
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)

方法二:前後枚舉

  • 對於每個位置 ii,從前往後乘一遍區間 [0,i][0, i] 的乘積到 a[i] 中
  • 對於每個位置 ii,從後往前乘一遍區間 (i,n)(i, n) 的乘積到 a[i] 中
class Solution {
    public int[] productExceptSelf(int[] A) {
        int n = A.length, l = 1, r = 1, a[] = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = l;
            l *= A[i];
        }
        for (int i = n-1; i >= 0; i--) {
            a[i] *= r;
            r *= A[i];
        }
        return a;
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章