|
| 1 | +- ๋ฌธ์ : https://leetcode.com/problems/product-of-array-except-self/ |
| 2 | +- time complexity : O(n) |
| 3 | +- space complexity : O(n) |
| 4 | +- ๋ธ๋ก๊ทธ ๋งํฌ : https://algorithm.jonghoonpark.com/2024/05/08/leetcode-238 |
| 5 | + |
| 6 | +## case ๋๋ ์ ํ๊ธฐ |
| 7 | + |
| 8 | +```java |
| 9 | +public int[] productExceptSelf(int[] nums) { |
| 10 | + int[] products = new int[nums.length]; |
| 11 | + int result = 1; |
| 12 | + int zeroCount = 0; |
| 13 | + |
| 14 | + int p = 0; |
| 15 | + while (p < nums.length) { |
| 16 | + if (nums[p] != 0) { |
| 17 | + result *= nums[p]; |
| 18 | + } else { |
| 19 | + zeroCount++; |
| 20 | + if (zeroCount >= 2) { |
| 21 | + Arrays.fill(products, 0); |
| 22 | + return products; |
| 23 | + } |
| 24 | + } |
| 25 | + p++; |
| 26 | + } |
| 27 | + |
| 28 | + if (zeroCount == 1) { |
| 29 | + p = 0; |
| 30 | + while (p < nums.length) { |
| 31 | + if (nums[p] == 0) { |
| 32 | + products[p] = result; |
| 33 | + } |
| 34 | + p++; |
| 35 | + } |
| 36 | + } else { |
| 37 | + p = 0; |
| 38 | + while (p < nums.length) { |
| 39 | + products[p] = result / nums[p]; |
| 40 | + p++; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return products; |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +## ์ฌ๋ฐ๋ ๋ฐฉ๋ฒ์ผ๋ก ํ๊ธฐ (prefixProd) |
| 49 | + |
| 50 | +```java |
| 51 | +public int[] productExceptSelf(int[] nums) { |
| 52 | + int[] result = new int[nums.length]; |
| 53 | + |
| 54 | + int[] prefixProd = new int[nums.length]; |
| 55 | + int[] suffixProd = new int[nums.length]; |
| 56 | + |
| 57 | + prefixProd[0] = nums[0]; |
| 58 | + for (int i = 1; i < nums.length; i++) { |
| 59 | + prefixProd[i] = prefixProd[i-1] * nums[i]; |
| 60 | + } |
| 61 | + |
| 62 | + suffixProd[nums.length - 1] = nums[nums.length - 1]; |
| 63 | + for (int i = nums.length - 2; i > -1; i--) { |
| 64 | + suffixProd[i] = suffixProd[i + 1] * nums[i]; |
| 65 | + } |
| 66 | + |
| 67 | + result[0] = suffixProd[1]; |
| 68 | + result[nums.length - 1] = prefixProd[nums.length - 2]; |
| 69 | + for (int i = 1; i < nums.length - 1; i++) { |
| 70 | + result[i] = prefixProd[i - 1] * suffixProd[i + 1]; |
| 71 | + } |
| 72 | + |
| 73 | + return result; |
| 74 | +} |
| 75 | +``` |
0 commit comments