File tree Expand file tree Collapse file tree 1 file changed +32
-1
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +32
-1
lines changed Original file line number Diff line number Diff line change 22
33// tag renovizee 2week
44// https://github.com/DaleStudy/leetcode-study/issues/239
5- // https://leetcode.com/problems/product-of-array-except-self/
5+ // https://leetcode.com/problems/product-of-array-except-self/ #238 #Medium
66class Solution {
77 // Solv1 :
88 // 시간복잡도 : O(n)
99 // 공간복잡도 : O(n)
1010 public int [] productExceptSelf (int [] nums ) {
1111
12+ boolean isZero = false ;
13+ int zeroIndex = 0 ;
14+
15+ int productExceptZero = 1 ;
16+ for (int i = 0 ; i < nums .length ; i ++) {
17+ if (nums [i ] == 0 ) {
18+ if (isZero ) { // zero가 2개면 모든 원소가 0임.
19+ return new int [nums .length ];
20+ }
21+ zeroIndex = i ;
22+ isZero = true ;
23+ } else {
24+ productExceptZero *= nums [i ];
25+ }
26+ }
27+
28+ int [] result = new int [nums .length ];
29+ for (int i = 0 ; i < nums .length ; i ++) {
30+ if (isZero ) {
31+ if (i != zeroIndex ) {
32+ result [i ] = 0 ;
33+ } else {
34+ result [i ] = productExceptZero ;
35+ }
36+ } else {
37+ result [i ] = productExceptZero / nums [i ];
38+ }
39+
40+ }
41+ return result ;
1242 }
43+
1344}
1445
1546//-------------------------------------------------------------------------------------------------------------
You can’t perform that action at this time.
0 commit comments