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. ์ต์ข ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค.
'Algorithm > Leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋งค์ผ LeetCode ํ๊ธฐ | Number of 1 bits (0) | 2024.08.19 |
---|---|
๋งค์ผ LeetCode ํ๊ธฐ | Sum of Two Integers (0) | 2024.08.18 |
๋งค์ผ LeetCode ํ๊ธฐ | Contains Duplicate (0) | 2024.08.14 |
๋งค์ผ LeetCode ํ๊ธฐ | Two Sum / Time to Buy and Sell Stock (0) | 2024.08.12 |
[Leetcode] Group Anagrams (0) | 2022.05.18 |