[Leetcode] 238. Product of Array Except Self
[Leetcode] 238. Product of Array Except Self

[Leetcode] 238. Product of Array Except Self

์–ธ์–ด
Python
C
๋‚œ์ด๋„
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•
์ž‘์„ฑ์ž
๋ฐ•์šฉ์„ฑ๋ฐ•์šฉ์„ฑ
์ƒ์„ฑ ์ผ์‹œ
2024๋…„ 06์›” 02์ผ
ย 

๐Ÿ–ฅ๏ธย ์‹œ์ž‘ํ•˜๋ฉฐ

๋ฌธ์ œ๋ฅผ ์š”์•ฝํ•˜๋ฉด, ์ถœ๋ ฅ๋˜๋Š” ๋ฐฐ์—ด์€ ๊ฐ ์ธ๋ฑ์Šค์˜ ์š”์†Œ๋ฅผ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ์ธ๋ฑ์Šค ์š”์†Œ๋“ค์˜ ๊ณฑ ์ด๋‹ค. ๊ทธ๋ž˜์„œ ๊ฐ€์žฅ ๋จผ์ € ์ ‘๊ทผํ•ด๋ณผ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ์‹์€ ์ด์ค‘ for๋ฌธ์„ ์ด์šฉํ•ด ๊ฐ ์ธ๋ฑ์Šค์˜ ์š”์†Œ๋ฅผ ์ œ์™ธํ•˜๊ณ  ๊ณฑ์„ ๊ตฌํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค.
class Solution: def calcMultiplex(self, nums: List[int]) -> int: sum = 1 for i in nums: sum *= i return sum def productExceptSelf(self, nums: List[int]) -> List[int]: res = [] for i in range(len(nums)): sum1 = self.calcMultiplex(nums[:i]) sum2 = self.calcMultiplex(nums[i + 1 :]) res.append(sum1 * sum2) return res
๋ฌผ๋ก  ๋‹น์—ฐํ•˜๊ฒŒ๋„ ๋ฌธ์ œ์—์„œ O(n) ๋ฐฉ์‹์œผ๋กœ ํ•ด๊ฒฐํ•˜๋ผ ํ–ˆ์œผ๋‹ˆ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋‚œ๋‹ค.
ย 
์ด ๋ฌธ์ œ๋ฅผ ์–ด๋–ป๊ฒŒ O(n) ์œผ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์ง€? ์ƒ๊ฐํ•˜๋‹ค, ๊ทธ๋ƒฅ ๊ณต๊ฐ„์„ ์กฐ๊ธˆ ๋” ์“ฐ๋ฉด ๋˜๊ฒ ๋‹ค๋Š” ์•„์ด๋””์–ด๊ฐ€ ๋‚˜์™”๋‹ค.
# ์ž…๋ ฅ : [1, 2, 3, 4] # ์™ผ์ชฝ ๋ˆ„์  ๊ณฑ ๊ณ„์‚ฐ for i in range(1, n): left[i] = left[i - 1] * nums[i - 1] # [1, 1, 2, 6] # ์˜ค๋ฅธ์ชฝ ๋ˆ„์  ๊ณฑ ๊ณ„์‚ฐ for i in range(n - 2, -1, -1): right[i] = right[i + 1] * nums[i + 1] # [24, 12, 4, 1]
ย 
์ด๋Ÿฐ ์‹์œผ๋กœ,
  1. ์™ผ์ชฝ๋ถ€ํ„ฐ ๋ณธ์ธ์˜ ์š”์†Œ๋ฅผ ์ œ์™ธํ•œ ๊ณฑ
  1. ์˜ค๋ฅธ์ชฝ๋ถ€ํ„ฐ ๋ณธ์ธ์˜ ์š”์†Œ๋ฅผ ์ œ์™ธํ•œ ๊ณฑ
์„ ๋ชจ๋‘ ๋ฏธ๋ฆฌ ๊ณ„์‚ฐํ•œ ๋‹ค์Œ, ์ด ๋‘˜์„ ๊ณฑํ•˜๋ฉด ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ค๊ฒŒ ๋œ๋‹ค.
ย 
ํ•˜๋‚˜ํ•˜๋‚˜ ๋œฏ์–ด๋ณด๋ฉด ์ดํ•ด๊ฐ€ ๊ฐˆ ๊ฒƒ์ด๋‹ค.. ๊ฒฐ๊ตญ ์™ผ์ชฝ๋ถ€ํ„ฐ ๊ณฑ๊ณผ ์˜ค๋ฅธ์ชฝ๋ถ€ํ„ฐ ๊ณฑ์€ ๋ณธ์ธ์„ ์ œ์™ธํ•œ ๊ณฑ์ด๋‹ˆ.
ย 

โš™๏ธย Python

from typing import List class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) left = [1] * n right = [1] * n res = [1] * n # ์™ผ์ชฝ ๋ˆ„์  ๊ณฑ ๊ณ„์‚ฐ for i in range(1, n): left[i] = left[i - 1] * nums[i - 1] # ์˜ค๋ฅธ์ชฝ ๋ˆ„์  ๊ณฑ ๊ณ„์‚ฐ for i in range(n - 2, -1, -1): right[i] = right[i + 1] * nums[i + 1] # ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ ๊ณ„์‚ฐ for i in range(n): res[i] = left[i] * right[i] return res s = Solution() print(s.productExceptSelf(nums=[1, 2, 3, 4]))

โš™๏ธย C++

#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> productExceptSelf(vector<int> &nums) { vector<int> left(nums.size()); vector<int> right(nums.size()); vector<int> res(nums.size()); for (int i = 1; i < nums.size(); ++i) left[i] = left[i - 1] * nums[i - 1]; for (int i = nums.size() - 2; i >= 0; --i) right[i] = right[i + 1] * nums[i + 1]; for (int i = 0; i < nums.size(); ++i) res[i] = left[i] * right[i]; return res; } };
ย 
ย 

๐Ÿ“Œย ์†Œ๊ฐ

ย 

๐Ÿ”ย ๋ถ€๋ก

๐Ÿ”ย ์ฐธ๊ณ ๋ฌธํ—Œ


ย 

๋Œ“๊ธ€

guest