題目:Product of Array Except Self
難度:Medium
我的解法
很暴力的把各種情境都列出來,還有簡化的空間
時間複雜度為 O(N),N 為矩陣長度;因 total、hasZeroCount 是常數已固定,故空間複雜度為 O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| public class Solution { public int[] ProductExceptSelf(int[] nums) { int total = 1; int hasZeroCount = 0; int[] result = new int[nums.Length];
for (int i = 0; i < nums.Length; i++) { if (nums[i] != 0) { total = total * nums[i]; } else { hasZeroCount = hasZeroCount + 1; } }
for (int i = 0; i < nums.Length; i++) { if (nums[i] != 0 && hasZeroCount == 0) { int num = total / nums[i]; result[i] = num; } else if (nums[i] != 0 && hasZeroCount > 0) { result[i] = 0; } if (nums[i] == 0 && hasZeroCount == 0) { result[i] = total; } else if (nums[i] == 0 && hasZeroCount > 0) { if (hasZeroCount > 1) { result[i] = 0; } else { result[i] = total; } } }
return result; } }
|
Dynamic Programming
看到有解題方式是用 Dynamic Programming space optimization
去解
還沒讀到 Dynamic Programming,先把解題方式記起來,之後再來看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class Solution { public int[] ProductExceptSelf(int[] nums) { int[] output = new int[nums.Length];
var pre = 1; for(int i = 0; i < nums.Length; i++) { output[i] = pre; pre *= nums[i]; }
var post = 1; for(int i = nums.Length - 1; i > -1; i--) { output[i] *= post; post *= nums[i]; }
return output; } }
|