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.
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
나눗셈 없이 해결하거나, 공간 최적화를 통해 푼다.
(1) 기본적인 방법 (O(N) 시간, O(N) 공간)
(2) 공간 최적화 (O(N) 시간, O(1) 추가 공간)
| 연산 | 복잡도 | 설명 |
|---|---|---|
| left_product 계산 | O(N) | 왼쪽 곱 계산 |
| right_product 곱하기 | O(N) | 오른쪽 곱 계산 |
| 총 시간 복잡도 | O(N) | 배열을 두 번 순회 |
| 추가 공간 복잡도 | O(1) | answer 배열 |
#include <iostream>
#include <vector>
using namespace std;
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> answer(n, 1); // 결과 배열 초기화
// Step 1: 왼쪽 곱 계산
int left_product = 1;
for (int i = 0; i < n; i++) {
answer[i] = left_product;
left_product *= nums[i]; // 현재 값까지 곱해서 왼쪽 곱 갱신
}
// Step 2: 오른쪽 곱 계산 및 결과 배열 업데이트
int right_product = 1;
for (int i = n - 1; i >= 0; i--) {
answer[i] *= right_product;
right_product *= nums[i]; // 현재 값까지 곱해서 오른쪽 곱 갱신
}
return answer;
}