Skip to content

Commit c4240c8

Browse files
committed
DaleStudy#239 product-of-array-except-self
1 parent 3549a8c commit c4240c8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
풀이 :
3+
해당 인덱스 이전 값들의 곱을 before에 저장(인덱스 0 이전에는 값이 없으므로 1로 초기화)
4+
해당 인덱스 이후 값들의 곱을 after에 저장(인덱스 n - 1이후에는 값이 없으므로 1로 초기화)
5+
인덱스 0부터 반복문을 돌며 ans에 인덱스 이전값들의 곱 before를 곱함 & before값에 현재 num을 곱함
6+
인덱스 끝부터 반복문을 돌며 after를 이용해 동일 작업
7+
8+
nums의 길이 : N
9+
10+
TC : O(N)
11+
반복문 2회 O(N + N)
12+
13+
SC : O(1) (ans배열 제외)
14+
N에 관계없이 before와 after 변수만 사용
15+
*/
16+
17+
#include <vector>
18+
using namespace std;
19+
20+
class Solution {
21+
public:
22+
vector<int> productExceptSelf(vector<int>& nums) {
23+
int before = 1;
24+
int after = 1;
25+
vector<int> ans(nums.size(), 1);
26+
27+
for (int i = 0; i < nums.size(); i++)
28+
{
29+
ans[i] *= before;
30+
before *= nums[i];
31+
}
32+
for (int i = nums.size() - 1; i >= 0; i--)
33+
{
34+
ans[i] *= after;
35+
after *= nums[i];
36+
}
37+
return ans;
38+
}
39+
};

0 commit comments

Comments
 (0)