File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode_study ;public class Geegong {
2
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .Arrays ;
2
+
3
+ public class Geegong {
4
+
5
+ /**
6
+ * Time complexity : O(n)
7
+ * Space complexity : O(1) (except result)
8
+ *
9
+ * νμ΄ : prefix array , suffix array λ₯Ό κ° λ°°μ΄λ§λ€ ꡬνμ¬ κ° arrayμ ν΄λΉλλ μΈλ±μ€μ κ°λ€μ κ³±νμ¬ κ²°κ³Όκ°μ λμΆ
10
+ *
11
+ * @param nums
12
+ * @return
13
+ */
14
+ public int [] productExceptSelf (int [] nums ) {
15
+
16
+ int [] result = new int [nums .length ];
17
+
18
+ // 1. result λ λ¨Όμ prefix λ°°μ΄λ€μ κ³±μΌλ‘ μ±μ΄λ€.
19
+ // ( prefix λ°°μ΄μ΄λ ν΄λΉλλ index μ΄μ μ λ°°μ΄μμκ°λ€μ μλ―Έ)
20
+
21
+ // μμμλΆν° λμ λλ μ΄ κ³±μ κ°
22
+ int accumulatedProduct = 1 ;
23
+ for (int index =0 ; index <nums .length ; index ++) {
24
+ if (index == 0 ) {
25
+ result [index ] = 1 ;
26
+ continue ;
27
+ }
28
+
29
+ result [index ] = accumulatedProduct * nums [index - 1 ];
30
+ accumulatedProduct = result [index ];
31
+ }
32
+
33
+ // 2. λ°°μ΄μ λ€μμλΆν° product of suffix κ°μ result λ°°μ΄ νλνλμ λ체νλ€.
34
+
35
+ // nums λ°°μ΄ μμμ λ€μμλΆν° λμ λλ μ΄ κ³±μ κ°
36
+ accumulatedProduct = 1 ;
37
+ for (int index =nums .length - 1 ; index >= 0 ; index --) {
38
+ if (index == nums .length - 1 ) {
39
+ accumulatedProduct = nums [index ];
40
+ continue ;
41
+ }
42
+
43
+ result [index ] = result [index ] * accumulatedProduct ;
44
+ accumulatedProduct = accumulatedProduct * nums [index ];
45
+ }
46
+
47
+ return result ;
48
+ }
49
+
50
+ }
You canβt perform that action at this time.
0 commit comments