Skip to content

Commit f4805ac

Browse files
committed
Add solution and test-cases for problem 238
1 parent ddaff67 commit f4805ac

File tree

3 files changed

+38
-21
lines changed

3 files changed

+38
-21
lines changed

leetcode/201-300/0238.Product-of-Array-Except-Self/README.md

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,25 @@
11
# [238.Product of Array Except Self][title]
22

3-
> [!WARNING|style:flat]
4-
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
5-
63
## Description
4+
Given an integer array `nums`, return an array `answer` such that `answer[i]` is equal to the product of all the elements of `nums` except `nums[i]`.
5+
6+
The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
7+
8+
You must write an algorithm that runs in `O(n)` time and without using the division operation.
79

810
**Example 1:**
911

1012
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
13+
Input: nums = [1,2,3,4]
14+
Output: [24,12,8,6]
1315
```
1416

15-
## 题意
16-
> ...
17+
**Example 2:**
1718

18-
## 题解
19-
20-
### 思路1
21-
> ...
22-
Product of Array Except Self
23-
```go
2419
```
25-
20+
Input: nums = [-1,1,0,-3,3]
21+
Output: [0,0,9,0,0]
22+
```
2623

2724
## 结语
2825

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,24 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func Solution(nums []int) []int {
4+
length := len(nums)
5+
r := make([]int, length)
6+
if length == 0 || length == 1 {
7+
return r
8+
}
9+
10+
r[0] = nums[0]
11+
for i := 1; i < length-1; i++ {
12+
r[i] = r[i-1] * nums[i]
13+
}
14+
r[length-1] = r[length-2]
15+
16+
rightProduct := nums[length-1]
17+
for idx := length - 2; idx > 0; idx-- {
18+
r[idx] = r[idx-1] * rightProduct
19+
rightProduct *= nums[idx]
20+
}
21+
r[0] = rightProduct
22+
23+
return r
524
}

leetcode/201-300/0238.Product-of-Array-Except-Self/Solution_test.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs []int
14+
expect []int
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase1", []int{1, 2, 3, 4}, []int{24, 12, 8, 6}},
17+
{"TestCase2", []int{-1, 1, 0, -3, 3}, []int{0, 0, 9, 0, 0}},
18+
{"TestCase3", []int{2, 3, 5, 0}, []int{0, 0, 0, 30}},
19+
{"TestCase4", []int{1, 1, 1}, []int{1, 1, 1}},
1920
}
2021

2122
// 开始测试

0 commit comments

Comments
 (0)