###### tags: `LeetCode`,`Java`,`Medium` # Medium-238. Product of Array Except Self ### **題目連結:** [**Product of Array Except Self**](https://leetcode.com/problems/product-of-array-except-self/description/) ### **解題方向** * 利用乘法的交換律和結合律,可以通過計算左側元素的乘積和右側元素的乘積來得出每個元素的乘積。 * 第一個循環計算每個元素左側元素的乘積,使用變量 c 記錄前綴乘積。 * 第二個循環計算每個元素右側元素的乘積,同時乘以前綴乘積。 * 最終得到的數組即為每個元素除自己以外其他所有數字的乘積。 ### **完整程式碼** ```java= class Solution { public int[] productExceptSelf(int[] nums) { int arr[]=new int[nums.length]; int c = 1; for(int i =0;i<nums.length;i++){ arr[i]=c; c*=nums[i]; } c = 1; for(int i =nums.length-1;i>=0;i--){ arr[i]*=c; c*=nums[i]; } return arr; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up