๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Leetcode

๋งค์ผ LeetCode ํ’€๊ธฐ | Product of Array Except Self

 

Product of Array Except Self

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
 
Example 1:
Input: nums = [1,2,3,4] Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]
 
Constraints:
2 <= nums.length <= 105-30 <= nums[i] <= 30The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

 

์ฒ˜์Œ ์ด ๋ฌธ์ œ๋ฅผ ํ’€๋ ค๊ณ  ํ–ˆ์„ ๋•Œ, ์ „์ฒด ๊ณฑ์„ ๊ณฑํ•œ ๋‹ค์Œ์— ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉด์„œ ๋‚˜๋ˆ—์…ˆ์„ ํ•˜๋ ค๊ณ  ํ–ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ์—ฌ๊ธฐ์„œ ๋‚˜๋ˆ—์…ˆ์„ ์“ฐ์ง€ ๋ง๋ผ๊ณ  ํ•˜์—ฌ.. ๊ธธ์„ ์žƒ๊ฒŒ ๋˜์—ˆ๊ณ  ๊ฒฐ๊ตญ์€ ํ˜ผ์ž ํž˜์œผ๋กœ ํ’€์ง€ ๋ชปํ–ˆ๋‹ค. 

 

์ด ๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š” ์ค‘์š” ์ ‘๊ทผ ๋ฐฉ์‹์€ ํˆฌํฌ์ธํ„ฐ์™€ ๋น„์Šทํ•œ ์ ‘๊ทผ ๋ฐฉ์‹์ด์—ˆ๋‹ค. 

 

class Solution {
    func productExceptSelf(_ nums: [Int]) -> [Int] {
        let n = nums.count
        var result = [Int](repeating: 1, count: n)

        var leftProduct = 1
        for i in 0..<n {
            result[i] *= leftProduct
            leftProduct *= nums[i]
        }

        var rightProduct = 1
        for i in (0..<n).reversed() {
            result[i] *= rightProduct
            rightProduct *= nums[i]
        }


        return result
    }
}

 

์ ‘๊ทผ ๋ฐฉ์‹ 
1. result ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด๋‘”๋‹ค. 
2. ์™ผ์ชฝ์—์„œ ์˜ค๋ฅธ์ชฝ์˜ ๋ˆ„์ ๊ณฑ์„ ๊ตฌํ•œ๋‹ค. 
3. ์˜ค๋ฅธ์ชฝ์—์„œ ์™ผ์ชฝ์˜ ๋ˆ„์ ๊ณฑ์„ ๊ตฌํ•œ๋‹ค. 
4. ์ตœ์ข… ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.