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]
.
Example:
Input:[1,2,3,4]
Output:[24,12,8,6]
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.)
這道題給定我們一個數組,讓我們返回一個新數組,對於每一個位置上的數是其他位置上數的乘積,並且限定了時間復雜度 O(n),並且不讓我們用除法。如果讓用除法的話,那這道題就應該屬於 Easy,因為可以先遍歷一遍數組求出所有數字之積,然后除以對應位置的上的數字。但是這道題禁止我們使用除法,那么我們只能另辟蹊徑。我們想,對於某一個數字,如果我們知道其前面所有數字的乘積,同時也知道后面所有的數乘積,那么二者相乘就是我們要的結果,所以我們只要分別創建出這兩個數組即可,分別從數組的兩個方向遍歷就可以分別創建出乘積累積數組。參見代碼如下:
C++ 解法一:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int n = nums.size(); vector<int> fwd(n, 1), bwd(n, 1), res(n); for (int i = 0; i < n - 1; ++i) { fwd[i + 1] = fwd[i] * nums[i]; } for (int i = n - 1; i > 0; --i) { bwd[i - 1] = bwd[i] * nums[i]; } for (int i = 0; i < n; ++i) { res[i] = fwd[i] * bwd[i]; } return res; } };
Java 解法一:
public class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] res = new int[n]; int[] fwd = new int[n], bwd = new int[n]; fwd[0] = 1; bwd[n - 1] = 1; for (int i = 1; i < n; ++i) { fwd[i] = fwd[i - 1] * nums[i - 1]; } for (int i = n - 2; i >= 0; --i) { bwd[i] = bwd[i + 1] * nums[i + 1]; } for (int i = 0; i < n; ++i) { res[i] = fwd[i] * bwd[i]; } return res; } }
我們可以對上面的方法進行空間上的優化,由於最終的結果都是要乘到結果 res 中,所以可以不用單獨的數組來保存乘積,而是直接累積到結果 res 中,我們先從前面遍歷一遍,將乘積的累積存入結果 res 中,然后從后面開始遍歷,用到一個臨時變量 right,初始化為1,然后每次不斷累積,最終得到正確結果,參見代碼如下:
C++ 解法二:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> res(nums.size(), 1); for (int i = 1; i < nums.size(); ++i) { res[i] = res[i - 1] * nums[i - 1]; } int right = 1; for (int i = nums.size() - 1; i >= 0; --i) { res[i] *= right; right *= nums[i]; } return res; } };
Java 解法二:
public class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length, right = 1; int[] res = new int[n]; res[0] = 1; for (int i = 1; i < n; ++i) { res[i] = res[i - 1] * nums[i - 1]; } for (int i = n - 1; i >= 0; --i) { res[i] *= right; right *= nums[i]; } return res; } }
Github 同步地址:
https://github.com/grandyang/leetcode/issues/238
類似題目:
參考資料:
https://leetcode.com/problems/product-of-array-except-self/
https://leetcode.com/problems/product-of-array-except-self/discuss/65638/My-simple-Java-solution