|
| 1 | +#์ด ๋ฌธ์ ๋ ๋ฐฐ์ด์ ๊ฐ ์์ i๋ฅผ ์ ์ธํ ๋๋จธ์ง ์์๋ค์ ๊ณฑ์ ๊ตฌํ๋ ๋ฌธ์ ์ |
| 2 | +#1)๊ฐ ์์ i๋ฅผ ๊ธฐ์ค์ผ๋ก ์ผ์ชฝ ์ซ์๋ค์ ๊ณฑ๊ณผ ์ค๋ฅธ์ชฝ ์ซ์๋ค์ ๊ณฑ์ ๋ฐ๋ก ๊ณ์ฐ, 2)์ต์ข
๊ฒฐ๊ณผ๋ ์ผ์ชฝ ๊ณฑ๊ณผ ์ค๋ฅธ์ชฝ ๊ณฑ์ ๊ณฑ |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def productExceptSelf(self, nums: List[int]): |
| 6 | + #์
๋ ฅ ๋ฐฐ์ด์ ๊ธธ์ด๋ฅผ ์ ์ฅ |
| 7 | + ##Example 1์ ๊ฒฝ์ฐ : len(nums) = 4 |
| 8 | + n = len(nums) |
| 9 | + #๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ๋ฐฐ์ด์ ๊ณฑ์
์ ํญ๋ฑ์์ธ 1๋ก ๋ชจ๋ ์ด๊ธฐํ |
| 10 | + #cf. ๋น ์งํฉ์ ๊ณฑ์ 1, ํฉ์ 0์ผ๋ก ์ ์๋จ |
| 11 | + ##answer = [1] * 4 = [1, 1, 1, 1] |
| 12 | + answer = [1] * n |
| 13 | + |
| 14 | + #i๋ฅผ ๊ธฐ์ค์ผ๋ก ์ผ์ชฝ ์ซ์๋ค์ ๊ณฑ์ ๊ณ์ฐ |
| 15 | + #์ผ์ชฝ ๊ณฑ์ ์ด๊ธฐ๊ฐ |
| 16 | + left_product = 1 |
| 17 | + for i in range(n): |
| 18 | + #ํ์ฌ ์์น์ ์ผ์ชฝ ๊ณฑ์ ์ ์ฅ |
| 19 | + ##nums[0]์ ์ผ์ชฝ์๋ ์๋ฌด ์ซ์๋ ์์ผ๋ฏ๋ก, |
| 20 | + ##์๋ฌด๊ฒ๋ ์๋ ์ํ์ ๊ณฑ์ 1์. ๋ฐ๋ผ์ answer[0]=1 |
| 21 | + ##answer[1]=1 / answer[2]=2 / answer[3]=6 |
| 22 | + answer[i] = left_product |
| 23 | + #๋ค์ ์์น๋ฅผ ์ํด ํ์ฌ ์๋ฅผ ๊ณฑํจ |
| 24 | + ##left_product = 1 * 1 = 1 / left_product = 1 * 2 = 2 |
| 25 | + ##left_product = 2 * 3 = 6 / left_product = 6 * 4 = 24 |
| 26 | + left_product *= nums[i] |
| 27 | + |
| 28 | + ##์ฒซ ๋ฒ์งธ for๋ฌธ ํ answer = [1, 1, 2, 6] |
| 29 | + #i๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฅธ์ชฝ ์ซ์๋ค์ ๊ณฑ ๊ณ์ฐ ๋ฐ ์ต์ข
๊ฒฐ๊ณผ ์์ฑ |
| 30 | + right_product = 1 |
| 31 | + #์ค๋ฅธ์ชฝ์์ ์ผ์ชฝ์ผ๋ก ์ํ |
| 32 | + for i in range(n-1, -1, -1): |
| 33 | + #ํ์ฌ ์์น์ ์ค๋ฅธ์ชฝ ๊ณฑ์ ์ ์ฅ |
| 34 | + ##answer[3] = 6 * 1 = 6 / answer[2] = 2 * 1 = 2 |
| 35 | + ##answer[1] = 1 * 1 = 1 / answer[1] = 1 * 1 = 1 |
| 36 | + answer[i] *= right_product |
| 37 | + #๋ค์ ์์น๋ฅผ ์ํด ํ์ฌ ์๋ฅผ ๊ณฑํจ |
| 38 | + ##right_product = 1 * 4 = 4 / right_product = 4 * 3 = 12 |
| 39 | + ##right_product = 12 * 2 = 24 / right_product = 24 * 1 = 24 |
| 40 | + right_product *= nums[i] |
| 41 | + |
| 42 | + |
| 43 | + #์ต์ข
๊ฒฐ๊ณผ๋ฅผ ๋ฐํ |
| 44 | + ##์ต์ข
answer = [24, 12, 8, 6] |
| 45 | + return answer |
| 46 | + |
| 47 | + #์๊ฐ ๋ณต์ก๋: O(n) |
| 48 | + ##๋ ๋ฒ์ ์ ํ ์ํ๋ง ์ํํ๋ฉฐ, ๊ฐ ์ํ๋ O(n) ์๊ฐ์ด ์์ |
| 49 | + #๊ณต๊ฐ ๋ณต์ก๋: O(1) |
| 50 | + ##์ถ๊ฐ์ ์ธ ๊ณต๊ฐ์ ์ฌ์ฉํ์ง ์์ |
| 51 | + ##๋จ, ์ถ๋ ฅ ๋ฐฐ์ด์ ๋ฌธ์ ์ ์๊ตฌ์ฌํญ์ด๋ฏ๋ก ์ ์ธ |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
0 commit comments