File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int [] productExceptSelf (int [] nums ) {
3+ /**
4+ 1. understanding
5+ - given integer array nums
6+ - product of which's all elements except that element
7+ - should be under O(N) time complexity
8+ - should not use division operation
9+ 2. strategy
10+ - brute force: O(n^2)
11+ - for every elements, calculate product of other elements
12+ - 1: 2 * [3 * 4]
13+ - 2: 1 * [3 * 4]
14+ - 3: [1 * 2] * 4
15+ - 4: [1 * 2] * 3
16+ - dynamic programming
17+ - assign array mem to memorize product till that idx
18+ - mem memorize in ascending order product value and reverse order product value
19+ 3. complexity
20+ - time: O(N)
21+ - space: O(N)
22+ */
23+ // 1. assign array variable mem
24+ int [][] mem = new int [nums .length ][];
25+ for (int i = 0 ; i < nums .length ; i ++) {
26+ mem [i ] = new int [2 ];
27+ }
28+
29+ // 2. calculate product values
30+ for (int i = 0 ; i < nums .length ; i ++) { // O(N)
31+ if (i == 0 ) {
32+ mem [i ][0 ] = nums [i ];
33+ continue ;
34+ }
35+ mem [i ][0 ] = nums [i ] * mem [i -1 ][0 ];
36+ }
37+
38+ for (int i = nums .length - 1 ; i >= 0 ; i --) { // O(N)
39+ if (i == nums .length - 1 ) {
40+ mem [i ][1 ] = nums [i ];
41+ continue ;
42+ }
43+ mem [i ][1 ] = nums [i ] * mem [i +1 ][1 ];
44+ }
45+
46+ int [] ret = new int [nums .length ];
47+ for (int i = 0 ; i < nums .length ; i ++) { // O(N)
48+ int left = (i - 1 ) >= 0 ? mem [i -1 ][0 ] : 1 ;
49+ int right = (i + 1 ) < nums .length ? mem [i +1 ][1 ] : 1 ;
50+ ret [i ] = left * right ;
51+ }
52+
53+ return ret ;
54+ }
55+ }
56+
You can’t perform that action at this time.
0 commit comments