Skip to content

Commit 940096f

Browse files
committed
feat: solve product Except self
1 parent 94d333f commit 940096f

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package leetcode_study
2+
3+
fun productExceptSelf(nums: IntArray): IntArray {
4+
// ex. nums = [1, 2, 3, 4]
5+
val leftStartProducts = mutableListOf(1)
6+
val rightStartProducts = mutableListOf(1)
7+
8+
// mutableNums = [1, 1, 2, 3, 4]
9+
val mutableNums = nums.toMutableList()
10+
mutableNums.add(0, 1)
11+
mutableNums.add(1)
12+
13+
// leftStartProducts = [1, 1, 2, 6, 24, 24]
14+
// rightStartProducts = [24, 24, 24, 12, 4, 1]
15+
for (idx in 1..< mutableNums.size) {
16+
val leftNum = mutableNums[idx]
17+
val rightNum = mutableNums[mutableNums.size - 1 - idx]
18+
19+
leftStartProducts.add(leftStartProducts.last() * leftNum)
20+
rightStartProducts.add(index = 0, element = rightStartProducts.first() * rightNum)
21+
}
22+
23+
val result = mutableListOf<Int>()
24+
for (idx in 0..mutableNums.size - 3) {
25+
result.add(leftStartProducts[idx] * rightStartProducts[idx + 2])
26+
}
27+
28+
return result.toIntArray()
29+
}

0 commit comments

Comments
 (0)