Skip to content

Commit 87824ac

Browse files
aQuaaQua
aQua
authored and
aQua
committed
238 adding
1 parent 38002ff commit 87824ac

File tree

3 files changed

+100
-0
lines changed

3 files changed

+100
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# [238. Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)
2+
3+
## 题目
4+
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
5+
6+
Solve it without division and in O(n).
7+
8+
For example, given [1,2,3,4], return [24,12,8,6].
9+
10+
Follow up:
11+
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
12+
13+
## 解题思路
14+
15+
见程序注释
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package Problem0238
2+
3+
func productExceptSelf(a []int) []int {
4+
l := len(a)
5+
res := make([]int, l)
6+
7+
p := 1
8+
zero := 0
9+
for i := 0; i < l; i++ {
10+
if a[i] == 0 {
11+
zero++
12+
continue
13+
}
14+
p *= a[i]
15+
}
16+
17+
if zero > 1 {
18+
return res
19+
}
20+
21+
for i := 0; i < l; i++ {
22+
if a[i] != 0 {
23+
res[i] = p / a[i]
24+
}
25+
}
26+
27+
return res
28+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package Problem0238
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type question struct {
11+
para
12+
ans
13+
}
14+
15+
// para 是参数
16+
type para struct {
17+
nums []int
18+
}
19+
20+
// ans 是答案
21+
type ans struct {
22+
one []int
23+
}
24+
25+
func Test_Problem0238(t *testing.T) {
26+
ast := assert.New(t)
27+
28+
qs := []question{
29+
30+
question{
31+
para{
32+
[]int{1, 2, 3, 4},
33+
},
34+
ans{
35+
[]int{24, 12, 8, 6},
36+
},
37+
},
38+
39+
question{
40+
para{
41+
[]int{0, 0, 0, 0},
42+
},
43+
ans{
44+
[]int{0, 0, 0, 0},
45+
},
46+
},
47+
48+
// 如需多个测试,可以复制上方元素。
49+
}
50+
51+
for _, q := range qs {
52+
a, p := q.ans, q.para
53+
fmt.Printf("~~%v~~\n", p)
54+
55+
ast.Equal(a.one, productExceptSelf(p.nums), "输入:%v", p)
56+
}
57+
}

0 commit comments

Comments
 (0)